<?php

define('SQL_FILE', 'weixin.sql');
define('DSQL_FILE', 'dweixin.sql');
//define('USER_AGENT_SERVICE', 'service');

// Customer User类
class CUserAction extends Action {
	/*
	 * 注册一个新用户，并同时创建customer
	 * 密码为base64编码
	 */
	public function register($email,$loginName, $password, $company,$agent='business',$contact=NULL,$phone=NULL,$wxNumber=NULL,$instantNumber=NULL,$address=NULL){
		$customer_user = D('customer_user');

		// 是否已经注册
		$where['loginName'] = $loginName;
// 		$where['email'] = $email;
		$result = $customer_user->where($where)->find();
		if (isset($result)) {
			Output::instance()->resultCode(code_user_exist);
			return;
		};
		$c_uuid =  Encryption::c_uuid();
		$token =  Encryption::token();

		if (C('USER_MAIL_MUST_VERIFY')) {
			// add customer
			$customer = D('customer');
			$customer->create();
			$customer->uuid = $c_uuid;
			$customer->token = $token;
			$customer->fullName = $company;
			$customer->profileUrl = DEFAULT_PROFILE_URL;
			$customerId = $customer->add();

            // 向wx_ind_media_info里添加一条isDefault的数据
            $IndMediaInfo_Model = D('ind_media_info');
            $ThirdPlatform_Model = D('third_platform');
            $third_platform_appid = $ThirdPlatform_Model->where(['name' => 'default'])->getField('appid');
            $data = [
                'cid' => $customerId,
                'uuid' => $c_uuid,
                'token' => $token,
                'expired' => date('Y-m-d H:i:s'),
                'isApiAuth' => 0,
                'isAutoGroup' => 0,
                'wxAppAccessExpiration' => 'null',
                'mode' => 0,
                'third_platform_appid' => $third_platform_appid,
                'type' => 1,
                'status' => 1,
                'needTailPic' => 0,
                'isDefault' => 1,
                'createTime' => date('Y-m-d H:i:s'),
                'deleted' => 0,
                'reviewer' => 0,
                'ifReview' => 0,
            ];
            $mediaId = $IndMediaInfo_Model->add($data);
            if (!is_numeric($mediaId)) {
                \Log::write('向自媒体添加账号失败:' . $IndMediaInfo_Model->getLastSql());
            }

			// add customer user
			$customer_user->create();
			$customer_user->customerId = $customerId;
			$customer_user->email = $email;
			$customer_user->loginName = $loginName;
			$customer_user->password = Encryption::password($password);
			$customer_user->profileUrl = DEFAULT_PROFILE_URL;
			$customer_user->fullName = $company;
			$customer_user->agent = $agent;
			$customer_user->activationKey = Encryption::uuid();

			$customer_user->contact = $contact;
			$customer_user->phone = $phone;
			$customer_user->wxNumber = $wxNumber;
			$customer_user->instantNumber = $instantNumber;
			$customer_user->address = $address;

			$customer_user->add();

			// 发送邮件
			Output::instance()->resultCode();
		}
		else {
			// add customer
			$customer = D('customer');
			$customer->create();
			$customer->uuid = $c_uuid;
			$customer->token = $token;
			$customer->fullName = $company;
			$customer->profileUrl = DEFAULT_PROFILE_URL;
			$customerId = $customer->add();

            // 向wx_ind_media_info里添加一条isDefault的数据
            $IndMediaInfo_Model = D('ind_media_info');
            $ThirdPlatform_Model = D('third_platform');
            $third_platform_appid = $ThirdPlatform_Model->where(['name' => 'default'])->getField('appid');
            $data = [
                'cid' => $customerId,
                'uuid' => $c_uuid,
                'token' => $token,
                'expired' => date('Y-m-d H:i:s'),
                'isApiAuth' => 0,
                'isAutoGroup' => 0,
                'wxAppAccessExpiration' => 'null',
                'mode' => 0,
                'third_platform_appid' => $third_platform_appid,
                'type' => 1,
                'status' => 1,
                'needTailPic' => 0,
                'isDefault' => 1,
                'createTime' => date('Y-m-d H:i:s'),
                'deleted' => 0,
                'reviewer' => 0,
                'ifReview' => 0,
            ];
            $mediaId = $IndMediaInfo_Model->add($data);
            if (!is_numeric($mediaId)) {
                \Log::write('向自媒体添加账号失败:' . $IndMediaInfo_Model->getLastSql());
            }

            // add customer user
			$customer_user->create();
			$customer_user->customerId = $customerId;
			$customer_user->email = $email;
			$customer_user->loginName = $loginName;
			$customer_user->password = Encryption::password($password);
			$customer_user->profileUrl = DEFAULT_PROFILE_URL;
			$customer_user->fullName = $company;
			$customer_user->agent = $agent;

			$customer_user->contact = $contact;
			$customer_user->phone = $phone;
			$customer_user->address = $address;
			$customer_user->wxNumber = $wxNumber;
			$customer_user->instantNumber = $instantNumber;
			$customer_user->updateTime = date('Y-m-d H:i:s');

			$customer_user->add();

			// 创建客户
			$this->create_customer($customerId);

			$result = new stdClass();
			$result->uuid = $c_uuid;
			$result->token = $token;
			$result->cid = $customerId;
			$result->role = 'C';
			$result->fullName = $company;
			$result->agent = $agent;
			$result->profileUrl = DEFAULT_PROFILE_URL;
			//Output::instance()->resultCode();
			Output::instance()->object($result);
		}
	}

	//vkey会员注册
	public function registerFroVkey($loginName,$password,$email,$templateId,$serviceId,$company,
										$agent='business',$contact=NULL,$phone=NULL,$wxNumber=NULL,$instantNumber=NULL){
		$customer_user = D('customer_user');
		// 是否已经注册
		$where['loginName'] = $loginName;
		$result = $customer_user->where($where)->find();
		if (isset($result)) {
			Output::instance()->resultCode(code_user_exist);
			return;
		};
		$c_uuid =  Encryption::c_uuid();
		$token =  Encryption::token();

		$model = new Model();
        $model->startTrans();
		$flag=false;
		$time = date("Y-m-d H:i:s");
		if (C('USER_MAIL_MUST_VERIFY')) {
			// add customer
			$customer = D('customer');
			$customer->create();
			$customer->uuid = $c_uuid;
			$customer->token = $token;
			$customer->fullName = $company;
			$customer->profileUrl = DEFAULT_PROFILE_URL;
			$customerId = $customer->add();

			// add customer user
			$customer_user->create();
			$customer_user->customerId = $customerId;
			$customer_user->email = $email;
			$customer_user->loginName = $loginName;
			$customer_user->password = Encryption::password($password);
			$customer_user->profileUrl = DEFAULT_PROFILE_URL;
			$customer_user->fullName = $company;
			$customer_user->agent = $agent;
			$customer_user->activationKey = Encryption::uuid();

			$customer_user->contact = $contact;
			$customer_user->phone = $phone;
			$customer_user->wxNumber = $wxNumber;
			$customer_user->instantNumber = $instantNumber;
			$customer_user->address = $address;

			$customer_user->add();

			// 发送邮件
			Output::instance()->resultCode();
		}
		else {
			// add customer
			$customerData["uuid"] = $c_uuid;
			$customerData["token"] = $token;
			$customerId = $model->table("wx_customer")->add($customerData);
			if(!$customerId){
				$flag = true;
			}
			if(!$flag){
				// add customer user
				$customerUserData["customerId"] = $customerId;
				$customerUserData["email"] = $email;
				$customerUserData["loginName"] = $loginName;
				$customerUserData["password"] = Encryption::password($password);
				$customerUserData["agent"] = $agent;
				$customerUserData["phone"] = $phone;
				$time = date('Y-m-d H:i:s');
				$customerUserData["updateTime"] = $time;
				$customerUserData["profileUrl"] = DEFAULT_PROFILE_URL;

				$customerUserData["fullName"] = $company;
				$customerUserData["contact"] = $contact;
				$customerUserData["wxNumber"] = $wxNumber;
				$customerUserData["instantNumber"] = $instantNumber;

				$customerUserId = $model->table("wx_customer_user")->add($customerUserData);
				if(!$customerUserId){
					$flag = true;
				}

			}
			// 创建客户
			if(!$flag){
				$importFlag = $this->create_customer($customerId);
				if(!$importFlag){
					$flag = true;
				}
			}

		if(!$flag){
			$model->commit();
			$result = new stdClass();
			$result->uuid = $c_uuid;
			$result->token = $token;
			$result->cid = $customerId;
			$result->role = 'C';
			$result->agent = $agent;
			$result->profileUrl = DEFAULT_PROFILE_URL;
			//fasong youjian
			/*
			$whereCustomerUser["customerId"] = $channelCustomerId;
			$whereCustomerUser["agent"] =  array(array('eq','agent'),array('eq','business'), 'or') ;
			$a = $customerUser->where($whereCustomerUser)->getField('`email`');
			*/
			$cuserArr = $customer_user->alias("user")
			->field("user.email")
			->join('wx_customer c on c.id = user.customerId')
			->where("user.agent='agent' and c.role='A'")
			->find();
			if($cuserArr){
				$title = "新用户注册";
				$message = "<br>您好：<br>系统中有新的账号注册。<br>注册信息：<br>账号：$loginName<br>邮箱：$email<br>".
				"联系人：$contact<br>联系方式：$phone<br>公众账号名称：$company<br>QQ：$instantNumber<br>微信号：$wxNumber<br>注册时间：$time";
				SendMail($cuserArr["email"],$title,$message,$ccAddress=null,$bccAddress=null);
			}
			Output::instance()->object($result);
		}else{
			$model->rollback();
			Output::instance()->resultCode(code_lackof_param);
		}


		}

	}



	public function forgetPassword($email,$loginName) {

		$CustomerUserModel = D('customer_user');

// 		$where['email'] = $email;
		$where['loginName'] = $loginName;
		$user = $CustomerUserModel->where($where)->find();

// 		$user = $customer_user->alias('cu')->where($where)
// 		->join('wx_customer c on c.id = cu.customerId')
// 		->field("cu.*,c.role,c.isApiAuth")->find();

		if (!isset($user)) {

			Output::instance()->resultCode(code_user_wrong_loginname);
			return;
		} else if($user['email'] == $email){

			//随机生成密码
			$password = generate_password(6);

			$user['updateTime'] = date('Y-m-d H:i:s');
			$user['password'] = Encryption::password($password);

			$id = $user['id'];

			$result = $CustomerUserModel->where("id=$id")->save($user);
			if ($result !== false) {
				try{
					//send email
					$title = C('FIND_PWD_TITLE');
					$content = C('FIND_PWD_CONTENT');
					//

	// 				$title='平台找回密码';
	// 				$newContent = '登录名:'.$loginName.' 密码是:'.$password;

					$newContent = str_replace(
							array('{LOGINNAME}','{PASSWORD}'),
							array($loginName,$password),
							$content
					);
					SendMail($email,$title,$newContent,NULL,EMAIL_BCCADRESS);

					Output::instance()->resultCode(code_success);
				} catch (Exception $e) {
					Log::write('用户找回密码发送邮件失败');
					Output::instance()->resultCode(code_sql_error);
				}
			} else {
				Output::instance()->resultCode(code_sql_error);
			}
		}else{
			Output::instance()->resultCode(code_user_wrong_email);
			return;
		}

	}

	public function deleteCustomer($customerId){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$ccid = Session::$user["customerId"];
		Session::switchCustomer(0);

		$Customer = D('customer');
		$CustomerUser = D('customer_user');
		$condition['id'] = array('eq',$customerId);
		$userCondition['customerId'] = array('eq',$customerId);
		$cu = $CustomerUser->where($userCondition)->find();

		// 删除该用户
		$Customer->where($condition)->delete();
		$CustomerUser->where($userCondition)->delete();


		// 删除客户表
		$this->delete_customer($customerId);

		Session::switchCustomer($customerId);

		$this->callProcedure($customerId);

        Output::instance()->resultCode(code_success, "删除成功");
        R('Log/add', array(module_handle_cuser, NULL, op_delete, '删除帐户' . $cu["loginName"]));
    }

	private function callProcedure($customerId) {
		$model = M("");
		$sql = "CALL wx_procedure_user_logicDel_public({$customerId});";
		$data = $model->query($sql);
	}

	/*
	 * 激活一个新用户，并同时初始化customer
	*/
	public function verify($key) {

		$customer_user = D('customer_user');
		$where['activationKey'] = $key;
		$user = $customer_user->where($where)->find();
		if (!isset($user)) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customer_user->activationKey = '';
		$customer_user->where($where)->save();

		// 创建客户
		$this->create_customer($user->customerId);
		Output::instance()->resultCode();
	}

    /**
     * @param $email
     * @param $loginName
     * @param $password
     * @param $company          /公司
     * @param $agent            /类型agent代理,business渠道,service员工
     * @param null $storeId     /门店id
     * @param null $storeName   /门店名
     * @param null $contact
     * @param null $phone       /手机
     * @param null $address     /地址
     * @param null $status
     * @param int $retype
     * @param null $customerId  /cid
     * @param null $groupId     /微信分组
     * @param null $qid         /圈id
     * @return mixed
     */
    public function addUser($email, $loginName, $password, $company, $agent,$storeId = NULL, $storeName = NULL,$contact = NULL,
                            $phone = NULL, $address = NULL, $status = NULL, $retype = 1, $customerId = NULL,$groupId=null,$qid=null,$tagIds=null,$vid = NULL)
    {
        if ($retype == 1) {
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }

            $customerId = Session::$user["customerId"];
            Session::switchCustomer(0);
        }

        if($agent == 'service' && $status == null){
            $status = 'open';
        }

        $date = date('Y-m-d H:i:s');
        $CustomerUser = D('customer_user');
        $CustomerTagListUser = D('customer_tag_list');
        // add customer user
        $CustomerUser->create();
        $CustomerUser->customerId = $customerId;
        $CustomerUser->email = $email;
        $CustomerUser->loginName = $loginName;
        $CustomerUser->password = Encryption::password($password);
        if ($retype == 2) {
            $CustomerUser->profileUrl = '';
        } else {
            $CustomerUser->profileUrl = DEFAULT_PROFILE_URL;
        }
        $CustomerUser->fullName = $company;
        $CustomerUser->agent = $agent;
        $CustomerUser->contact = $contact;
        $CustomerUser->phone = $phone;
        $CustomerUser->address = $address;
        $CustomerUser->status = $status;

        /*加入分组及营销圈*/
        $CustomerUser->groupId = $groupId;
        $CustomerUser->qid = $qid;
        $CustomerUser->vid = $vid;

        if ($storeId != NULL) {
            $CustomerUser->storeId = $storeId;
        }
        if ($storeName != NULL) {
            $CustomerUser->storeName = $storeName;
        }

        $CustomerUser->updateTime = $date;
        //$CustomerUser->registered=$date;
        $where['loginName'] = array('eq', $loginName);
        $where['customerId'] = $customerId;
        $res = $CustomerUser->where($where)->find();
        //var_dump($CustomerUser->getLastSql());exit;
        if ($res) {
            if ($retype == 1) {
                Output::instance()->resultCode(code_user_exist);
                return;
            } else if ($retype == 2) {
                $result = [
                    'code' => 1,
                    'msg' => '用户已存在',
                    'data' => []
                ];
                return $result;
            }

        }

        $id = $CustomerUser->add();
        $sql = $CustomerUser->getLastSql();
        if($tagIds){
            $tagIds = explode(',',$tagIds);
            foreach($tagIds as $v){
                $data['cid'] = $customerId;
                $data['uid'] = $id;
                $data['tagId'] = $v;
                $CustomerTagListUser->add($data);
            }
        }
        if(!$id){
            Log::write('error----sql-'.$CustomerUser->getLastSql());
        }

        if ($retype == 1)
            Session::switchCustomer($customerId);

        $result = new stdClass();
        $result->id = $id;
        $result->customerId = $customerId;
        $result->email = $email;
        $result->loginName = $loginName;
        $result->agent = $agent;
        $result->fullName = $company;
        if ($retype == 2) {
            $result->profileUrl = '';
        } else {
            $result->profileUrl = DEFAULT_PROFILE_URL;
        }

        $result->status = $status;

        if ($storeId != NULL) {
            $result->storeId = $storeId;
        }
        if ($storeName != NULL) {
            $result->storeName = $storeName;
        }
        //$result->registered = $date;
        if ($retype == 1) {
            if ($agent == 'service') {
                R('Log/add', array('employeeManage', '', '员工管理', op_add, $sql, '添加员工：' . $company));
            }
            Output::instance()->object($result);
        } else {
            return $id;
        }

    }

	public function deleteUser($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');
		$condition['id'] = array('eq',$id);

		// 删除该用户
        $agent = $CustomerUser->where($condition)->getField('agent');
        $company = $CustomerUser->where($condition)->getField('fullName');
		$CustomerUser->where($condition)->delete();
        $sql = $CustomerUser->getLastSql();
        if ($agent == 'service') {
            R('Log/add', array('employeeManage', '', '员工管理', op_delete, $sql, '删除员工：' . $company));
        }

		Output::instance()->resultCode(code_success,"删除成功");
	}

	public function changeUserPwd($oldpwd, $newpwd) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$id = session('id');
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUserModel = D('customer_user');
		$user = $CustomerUserModel->find($id);
		if ($user) {
			$confirmPwd = Encryption::password($oldpwd);
			if ($confirmPwd != $user["password"]) {
				Output::instance()->resultCode(code_user_oldpwd);
				return;
			}
			$data["password"] =  Encryption::password($newpwd);
			$result = $CustomerUserModel->where("id=$id")->save($data);
			if ($result !== false) {
				Output::instance()->resultCode();
			} else {
				Output::instance()->resultCode(code_sql_error);
			}
		} else {
			Output::instance()->resultCode(code_user_not_exist);
		}
	}

    public function updateUser($id, $email, $loginName, $password = '', $company, $agent,
                               $storeId = NULL, $storeName = NULL,
                               $contact = NULL, $phone = NULL, $address = NULL, $retype = 1, $cid = '', $type = NULL,$groupId=null,$qid=null,$tagIds=null,$vid = NULL)

    {
        if ($retype == 1) {
            $retVal = Session::init();
            if (!$retVal) {
                Output::instance()->resultCode(code_access_denied);
                return;
            }
            $cid = Session::$user["customerId"];
            Session::switchCustomer(0);
        }
        Session::switchCustomer(0);
        $CustomerUser = D('customer_user');
        $CustomerTagListUser = D('customer_tag_list');
        $ggUser = D('gg_user');
        // add customer user
        $data = array();

        $data['loginName'] = $loginName;
        if ($retype == 2) {
            $res = R('GgUser/judgeLoginName', array($cid, $loginName, 2));
            if ($res['code'] == 1) {
                Output::instance()->object($res);
                return;
            }

        }

        if ($password != "") {
            $data['password'] = Encryption::password($password);
        }
        if (!empty($company)) {
            $data['fullName'] = $company;
        } else {
            $data['fullName'] = $loginName;
        }

        $data['updateTime'] = date('Y-m-d H:i:s');
        if ($retype == 1) {
            $data['phone'] = $phone;
            $data['email'] = $email;
            $data['agent'] = $agent;
            $data['address'] = $address;
            $data['profileUrl'] = DEFAULT_PROFILE_URL;
            $data['storeId'] = $storeId;
            $data['storeName'] = $storeName;
            $data['contact'] = $contact;
            $data['vid'] = $vid;

            $where['loginName'] = $loginName;
            $where['customerId'] = $cid;
            $res = $CustomerUser->where($where)->find();

            if ($res != '' && $res['id'] != $id) {
                Output::instance()->resultCode(code_user_exist);
                return;
            }
            $CustomerTagListUser->where(['uid' => $id, 'cid' => $cid])->delete();
            if($tagIds){
                $tagIds = explode(',',$tagIds);
                foreach($tagIds as $v){
                    $data['cid'] = $cid;
                    $data['uid'] = $id;
                    $data['tagId'] = $v;
                    $CustomerTagListUser->add($data);
                }
            }
        }
        if($groupId){
            //$groupId=null,$qid=null
            $data['groupId'] = $groupId;
        }

        if($qid){
            $data['qid']= $qid;
        }

        $isOk = $CustomerUser->where('id=' . $id)->save($data);
        $sql = $CustomerUser->getLastSql();
        $person = $CustomerUser->where('id=' . $id)->find();
        //var_dump($isOk);
        if ($isOk !== false) {
            // 返回更新的数据
            $result = new stdClass();
            $result->id = $id;
            $result->email = $email;
            $result->fullName = $company;
            $result->agent = $agent;

            $result->storeId = $storeId;
            $result->storeName = $storeName;

            if ($retype == 1) {
                if ($agent == 'service') {
                    R('Log/add', array('employeeManage', '', '员工管理', op_update, $sql, '修改员工信息：' . $company));
                }
                Output::instance()->object($result);
            } else {
                $login['userId'] = $id;
                $login['customerId'] = $cid;
                if ($type == 'phone') {
                    R("GgGrade/dealBindGrade",array('bindPhone',$login));
                }else if ($type == 'weixin') {
                    R("GgGrade/dealBindGrade",array('bindWeixin',$login));
                }
                $CustomerUser->where("id=$id")->setField('status', 'open');
                $ggUser->where("cuid=$id")->setField('isComplete', '1');
                $session = Session::setCurrentUser($person);
                $person['session_id'] = $session->session_id;
                R('Gg/_retback', array($person));
            }

        } else {
            Output::instance()->resultCode(code_success, "更新失败");
        }
    }

	/**
	 * 根据门店,或者登录名查询员工
	 */
	public function getServiceUserByCondition($email=NULL,$storeName=NULL,$order="registered", $orderBy="desc", $start=0, $limit=25){
		$CustomerUserModel = M("customer_user");

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user['customerId'];

		if($storeName != NULL){
			$condition['storeName'] = array('like',"%$storeName%");
		}
		if($email != NULL){
			$condition['email'] = array('like',"%$email%");
		}
		$condition['customerId'] = array('eq',$customerId);
		$condition['agent'] = array('eq', USER_AGENT_SERVICE);

		$arr = $CustomerUserModel->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
		$count = $CustomerUserModel->where($condition)->count();

		if($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success,"没有用户");
		}
	}


	/**
	 * 返回某个customer_user管理的service列表
	 */
	public function getUserList($fullName='',$loginName='',$storeName='',$agent,$order="registered", $orderBy="desc", $start=0, $limit=25){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');
		!empty($fullName) ? $condition['fullName'] = array('like','%'.$fullName.'%') :'';
		!empty($loginName) ? $condition['loginName'] = array('like','%'.$loginName.'%') :'';
		!empty($storeName) ? $condition['storeName'] = array('like','%'.$storeName.'%') :'';
		$condition['customerId'] = array('eq',$customerId);
		$condition['agent'] = array('eq',$agent);

		$arr = $CustomerUser->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
		//echo $CustomerUser -> getLastSql();
		$count = $CustomerUser->where($condition)->count();

		Session::switchCustomer($customerId);

		if($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success,"没有用户");
		}

	}
	/*
	 * 用户登录，并返回一个session id
	*/
	public function login($email, $password, $cid = '') {

		$customer_user = D('customer_user');
		$role = D('customer_user_role');
 		//$where['email'] = $email;
		$where['email'] = array('eq', $email);
		$where['loginName'] = array('eq', $email);
		$where['phone'] = array('eq', $email);
		$where['_logic'] = "OR";
		$map["_complex"] = $where;
		$map['activationKey'] = array('exp', ' is NULL');

//		$where['password'] = Encryption::password($password);
		if(!empty($cid)){
			$map['customerId'] = array('eq',$cid);
		}

		// service can login, 微社区需要, 后台是否可以操作，后台判断
        $map['agent'] = array('neq','service');
		$user = $customer_user->alias('cu')->where($map)
		->join('wx_customer c on c.id = cu.customerId')
        ->join('wx_customer_weixin_profile b on c.id=b.cid')
		->field("cu.*,c.role,c.isApiAuth,c.appid,c.mode,b.grantStatus")->find();
		Log::write("user login password:\r\n".Encryption::password($password));
		if (!isset($user)) {
			Output::instance()->resultCode(code_user_not_exist);
			return;
		} else if (strcasecmp($user['password'], Encryption::password($password)) != 0 ) {
			Output::instance()->resultCode(code_user_wrong_pwd);
			return;
		}else if(strcasecmp($user['status'], 'open') != 0){
			Output::instance()->resultCode(code_user_status_invalid);
			return;
		}
		$arr_Role = $role
			->alias('cur')
			->join('wx_role r ON r.id = cur.roleId')
			->where(['userId' => $user['id']])
			->field('roleId, englishRole')
			->select();

		$arr_roleId = array_unique(array_filter(array_column($arr_Role, 'roleId')));  // 去除数组中的空值
		$arr_englishRole = array_unique(array_filter(array_column($arr_Role, 'englishRole')));
		$agentId = implode(',', $arr_roleId);
		$agent = implode(',', $arr_englishRole);
		$user['agentId'] = $agentId;
		$user['agent'] = $agent;



		$session = Session::setCurrentUser($user);

		$result = new stdClass();
		$result->fullName = $user['fullName'];
		$result->agent = $user['agent'];
		$result->agentId = $user['agentId'];
		$result->customerId = $user['customerId'];
		$result->userId = $user['id'];
		$result->status = $user['status'];
        $result->mode = $user['mode'];
        $result->grantStatus = $user['grantStatus'];
		$result->role = $user['role'];
        $result->appid = $user['appid'];
		$result->session_id = $session->session_id;
		
		Output::instance()->object($result);
	}

	/*
	 * 用户退出登录,返回一个bool值
	 */
	public function logout(){
		$result = Session::clearCurrentUser();
		Output::instance()->resultCode();
	}

	public function isAdmin() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$result = new stdClass();
		$result->cid = Session::$user["customerId"] ;
		Output::instance()->object($result);
	}

	public function adminSwitch($loginName) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$role = Session::$user['role'];
		$agent = Session::$user['agent'];
		//如果是平台管理员或者平台运营管理员则可以进行操作
		if (Session::isAgent() || in_array(role_operate, explode(',', $agent))) {
				$customerId = Session::$user["customerId"];

				Session::switchCustomer(0);
				$customer_user = D('customer_user');
                 $role = D('customer_user_role');

			$where['loginName'] = $loginName;
				$where['activationKey'] = array('exp',' is NULL');
				$where['agent'] = array(array('eq','agent'),array('eq','business'), 'or');
				$user = $customer_user->alias('cu')->where($where)
				->join('wx_customer c on c.id = cu.customerId')
				->join('wx_customer_weixin_profile b on c.id=b.cid')
				->field("cu.*,c.role,c.isApiAuth,c.appid,c.mode,b.grantStatus")->find();
				Session::switchCustomer($customerId);
				if (!isset($user)) {
					Output::instance()->resultCode(code_user_not_exist);
					return;
				} else if(strcasecmp($user['status'], 'open') != 0){
					Output::instance()->resultCode(code_user_status_close);
					return;
				}

				$arr_Role = $role
						->alias('cur')
						->join('wx_role r ON r.id = cur.roleId')
						->where(['userId' => $user['id']])
						->field('roleId, englishRole')
						->select();

				$arr_roleId = array_unique(array_filter(array_column($arr_Role, 'roleId')));  // 去除数组中的空值
				$arr_englishRole = array_filter(array_column($arr_Role, 'englishRole'));
				$agentId = implode(',', $arr_roleId);
				$agent = implode(',', $arr_englishRole);
				$user['agentId'] = $agentId;
				$user['agent'] = $agent;

				$user["loginName"] = Session::$user["loginName"];
				$session = Session::setCurrentUser($user);

				$result = new stdClass();
				$result->fullName = $user['fullName'];
				$result->agent = $user['agent'];
				$result->customerId = $user['customerId'];
				$result->userId = $user['id'];
                		$result->appid = $user['appid'];
				$result->status = $user['status'];
                		$result->mode = $user['mode'];
				$result->grantStatus = $user['grantStatus'];
				$result->role = $user['role'];
				$result->session_id = $session->session_id;
		}
		Output::instance()->object($result);
	}
	/**
	 * 返回运营agent用户列表
	 * 或者账号business用户列表
	 */
	public function getAgentUserList($agent,$loginName='',$status='',$fullName='',$order="registered", $orderBy="desc", $start=0, $limit=25){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

        /** 0. 判断是不是超级管理员 */
        $isAdmin = Session::isAdmin();
        if (!$isAdmin) {
            Output::instance()->resultCode(code_user_priv_invalid);
            exit();
        }

		$customerId = Session::$user["customerId"];
		$customerUserId = Session::$user["id"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');
		$Customer = D('customer');
		//如果是运营管理员查看管理员列表，则显示分配给他的用户
		if($agent == 'all'){//返回渠道和客户列表
			$condition['cu.agent'] = array(array('eq','agent'),array('eq','business'), 'or') ;
		}else{
			$condition['cu.agent'] = array('eq',$agent);
		}
		!empty($fullName) ? $condition['cu.fullName'] = array('like','%'.$fullName.'%'):'';
		!empty($loginName) ? $condition['cu.loginName'] = array('like','%'.$loginName.'%'):'';
		!empty($status) ? $condition['cu.status'] = array('eq',$status):'';
		$arr = $CustomerUser->alias("cu")
		->field("cu.*")
		->where($condition)
		->order("$order $orderBy")
		->limit("$start,$limit")
		->select();
 		//echo $CustomerUser->getLastSql();
		$count = $CustomerUser
			->alias("cu")
			->field("cu.*")
			->where($condition)->count();

		Session::switchCustomer($customerId);
		if($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success,"没有用户");
		}

	}
	/**
	 * 返回某个运营agent用户管理的账号business用户列表
	 */
	public function getAgentBusinessUserList($cid,$order="registered", $orderBy="desc", $start=0, $limit=25){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUserRelation = D('customer_user_relation');
		$CustomerUser = D('customer_user');

		$condition['cur.customerId'] = array('eq',$cid);
		$arr = $CustomerUserRelation->alias('cur')
		->where($condition)
		->join('wx_customer_user cu on cur.customerUserId = cu.id')
		->order("$order $orderBy")->limit("$start,$limit")
		->field('cu.*')->select();

		$cCon['customerId'] = array('eq',$cid);
		$cCon['agent'] = array('eq','agent');
		$selfUser = $CustomerUser->where($cCon)->find();
		array_unshift($arr,$selfUser);

		$count = $CustomerUserRelation->alias('cur')
		->where($condition)
		->join('wx_customer_user cu on cur.customerUserId = cu.id')
		->count();
		$count = $count +1;

		Session::switchCustomer($customerId);

		if($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success,"没有用户");
		}

	}

	/**
	 * 取消运营用户,恢复为普通账号
	 */
	public function deleteAgent($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');
		$condition['id'] = array('eq',$id);

		$result = $CustomerUser->where($condition)->setField("agent", "business");

		if($result){
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_success);
		}else{
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_sql_error);
		}

	}
	/**
	 * 添加普通账号为运营用户
	 */
	public function addAgent($id){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');
		$condition['id'] = array('eq',$id);

		$result = $CustomerUser->where($condition)->setField("agent", "agent");

		if($result){
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_success);
		}else{
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_sql_error);
		}
	}
	/**
	 * 修改customer_user状态
	 */
	public function updateCustomerUserStatus($id,$status,$customerTempId=0,$regCustomerId=0){
		set_time_limit(0);
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		$agent = Session::$user["agent"];
		Session::switchCustomer(0);

		$CustomerUserModel = D('customer_user');
		$roleModel = D('role');
		$condition['id'] = array('eq',$id);
		$customerUser = $CustomerUserModel->where($condition)->find();
		if (!$customerUser) {
			Output::instance()->resultCode(code_customer_not_exit);
			return;
		}
		$result = $CustomerUserModel->where($condition)->setField("status", $status);
		if($result){
			if($status == 'open'){
				if("agent"!=$agent){
					//导入行业模板数据
					$importDataResult = $this->importDateToTemplate($customerTempId,$regCustomerId);
				}
				$this->sendMailToCustomer($customerUser);
				$cid = $CustomerUserModel->where($condition)->getField("customerId");
				$roleArr = $roleModel->where(['cid' => $cid])->select();

				if(empty($roleArr)){
					$this->customerInitialRole($cid);
					$this->customerBusinessRole($cid,$id);
				}
				$logDetail = "开启帐号";
			} else {
				$logDetail = "停用帐号";
			}

			R('Log/add', array(module_handle_cuser, NULL, op_update, $logDetail . $customerUser["loginName"]));
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_success);
		}else{
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_sql_error);
		}
	}


	private function sendMailToCustomer($customerUser) {
		//发送邮件
		$RegisterSettingModel = D('customer_register_setting');
		$setting = $RegisterSettingModel->limit("0,1")->find();

		if(!$setting || empty($setting["successContent"])){
			Log::write("[CUser sendMailToCustomer not set]");
			return;
		}

		if($customerUser){
			$email = $customerUser['email'];
			$fullName = $customerUser['fullName'];
			$loginName = $customerUser['loginName'];
			$contact = $customerUser['contact'];
			$phone = $customerUser['phone'];
			$wxNumber = $customerUser['wxNumber'];
			$instantNumber = $customerUser['instantNumber'];

			// 							$title = SUCCESS_EMAIL_TITLE;
			$title = $setting['successWebPageName'];

			$Customer = D('customer');
			$customerCondition['id'] = array('eq',$customerUser['customerId']);
			$customer = $Customer->where($customerCondition)->find();

			if($customer){
				$uuid = $customer['uuid'];
				$token = $customer['token'];
				$deepUrl = C('SERVER_HOST');
				$url = $deepUrl.'Callback.json?id='.$uuid;
				$content = str_replace(
						array('{URL}','{token}','{fullName}','{loginName}','{contact}', '{phone}','{wxNumber}','{instantNumber}'),
						array($url,$token,$fullName,$loginName,$contact,$phone,$wxNumber,$instantNumber),
						$setting['successContent']
				);
				// 									$deepUrl = "http://localhost";
				$newContent = relative_to_absolute($content,$deepUrl);
				try {
					SendMail($email,$title,$newContent,NULL,EMAIL_BCCADRESS);
				} catch (Exception $e) {
					Log::write('开启用户发送邮件失败');
				}
			}
		}
	}

	/**
	 * 为某运营用户添加管理的普通账号
	 */
	public function addAgentBusiness($cuid,$cid){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUserRelation = D('customer_user_relation');
		$data['customerUserId'] = $cuid;
		$data['customerId'] = $cid;
		$data['updateTime'] = date('Y-m-d H:i:s');

		$result = $CustomerUserRelation->add($data);

		if($result){
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_success);
		}else{
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_sql_error);
		}

	}
	public function deleteAgentBusiness($cuid,$cid){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUserRelation = D('customer_user_relation');
		$condition['customerUserId'] = array('eq',$cuid);
		$condition['customerId'] = array('eq',$cid);

		$result = $CustomerUserRelation->where($condition)->delete();

		if($result){
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_success);
		}else{
			Session::switchCustomer($customerId);
			Output::instance()->resultCode(code_sql_error);
		}

	}


	public function create_customer($customerId) {
		Session::switchCustomer($customerId);
		return Module::importSQL(DATABASE_PATH . SQL_FILE);
	}

	public function delete_customer($customerId){
		Session::switchCustomer($customerId);
		return Module::importSQL(DATABASE_PATH . DSQL_FILE);

	}

	/*
	 *	获取当前登录用户信息
	 */
	public function getUserInfo() {
		$customerUserModel = D('customer_user');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$id = session('id');
		$result = $customerUserModel->alias('cu')->where("cu.id=$id")->join('wx_customer on wx_customer.id = cu.customerId')->find();
// 		echo $customerUserModel->getLastSql();
		if (!isset($result)) {
			Output::instance()->resultCode(code_user_not_exist);
			return;
		}
		Output::instance()->object($result);
	}

	/**
	 *	获取账号用户信息
	 */
	public function getUserInfoById($id) {
		$customerUserModel = D('customer_user');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$result = $customerUserModel->alias('cu')->where("cu.id=$id")->join('wx_customer on wx_customer.id = cu.customerId')->find();
// 		echo $customerUserModel->getLastSql();
		if (!isset($result)) {
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		Output::instance()->object($result);
	}

	/**
	 *	获取账号用户信息
	 */
	public function getUserInfoValueByCustomerId() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$customerUserModel = D('customer');
		$result = $customerUserModel->alias('customer')->where("customer.id=$customerId")->join('wx_customer_user cu on customer.id = cu.customerId')->field("cu.*")->find();
// 		Log::write($customerUserModel->getLastSql()) ;
		if (!isset($result)) {
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		Session::switchCustomer($customerId);
		return $result;
	}

	/*
	 * loginName：不允许修改登录名
	*/
	public function userChange($email,$company, $password = '', $appId = NULL, $appSecret= NULL, $isApiAuth = false, $contact=NULL,$phone=NULL,$wxNumber=NULL,$instantNumber=NULL,$address=NULL, $loginName='',$wxAppAppid='',$wxAppSecret='') {
		$customerUserModel = D('customer_user');
		$customerModel = D('customer');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		// change customer user
		$user['email'] = $email;
// 		$user['loginName'] = $loginName;
		$user['contact'] = $contact;
		$user['phone'] = $phone;
		$user['wxNumber'] = $wxNumber;
		$user['instantNumber'] = $instantNumber;
		$user['address'] = $address;
		$user['updateTime'] = date('Y-m-d H:i:s');
		$user['fullName'] = $company;

		if ($password != '') {
			$user['password'] = Encryption::password($password);
		}
		$id = session('id');
		$customerUserModel->where("id=$id")->save($user);

		$customer['appid'] = empty($appId) ? NULL : trim($appId);
		$customer['appsecret'] = empty($appSecret) ? NULL : trim($appSecret);
		$customer['isApiAuth'] = $isApiAuth;
		$customer['accessToken'] = NULL;
		$customer['accessExpiration'] = 0;
		$customer['wxAppAppid'] = empty($wxAppAppid) ? NULL : trim($wxAppAppid);
		$customer['wxAppSecret'] = empty($wxAppSecret) ? NULL : trim($wxAppSecret);

		$cid = Session::$user["customerId"];
		$result = $customerModel->where("id=$cid")->save($customer);
		if ($result !== false) {
			Output::instance()->resultCode(code_success);
		} else {
			// 		Log::write($customerModel->getLastSql());
			Output::instance()->resultCode(code_sql_error);
		}
	}


    /**
     * 客户物流以及付费方式,绑定会员卡等配置
     */
    public function updateCustomerSuperSetting($cid, $allowPickUp, $allowDelivery,
                                               $allowWXPay, $allowAlipay, $allowDeliveryPay, $allowStored, $allowTransfer, $allowUPay, $allowTenPay,
                                               $isBindingMemberObject, $url, $token, $msgSerialNumber, $msgPwd,
                                               $allowBuyMenu, $buyMenuPosition, $buyMenuName, $buyMenuUrl, $vendorLimit,$allowSystemSms='',$allowAiNongPay)
    {

        $CustomerSuperSettingModel = D('customer_super_setting');
        $user = D('customer_user');
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $data["allowPickUp"] = $allowPickUp === 'true' ? true : false;
        $data["allowDelivery"] = $allowDelivery === 'true' ? true : false;
        $data["allowWXPay"] = $allowWXPay === 'true' ? true : false;
        $data["allowAlipay"] = $allowAlipay === 'true' ? true : false;
        $data["allowAiNongPay"] = $allowAiNongPay === 'true' ? true : false;
        $data["allowDeliveryPay"] = $allowDeliveryPay === 'true' ? true : false;
        $data["allowStored"] = $allowStored === 'true' ? true : false;
        $data["allowTransfer"] = $allowTransfer === 'true' ? true : false;
        $data["allowUPay"] = $allowUPay === 'true' ? true : false;
        $data["allowTenPay"] = $allowTenPay === 'true' ? true : false;
        $data["isBindingMemberObject"] = $isBindingMemberObject === 'true' ? true : false;
        $data["allowSystemSms"] = $allowSystemSms === 'true' ? true : false;
        $data["allowSystemSms"] = $allowSystemSms === 'true' ? true : false;

        $data["allowBuyMenu"] = $allowBuyMenu === 'true' ? true : false;

        if ($url == null) {

            $data['url'] = NULL;
        } else {
            $data['url'] = $url;
        }

        if ($token == null) {
            $data['token'] = NULL;
        } else {
            $data['token'] = $token;
        }
        if ($msgSerialNumber == null) {
            $data['msgSerialNumber'] = NULL;
        } else {
            $data['msgSerialNumber'] = $msgSerialNumber;
        }
        if ($msgPwd == null) {
            $data['msgPwd'] = NULL;
        } else {
            $data['msgPwd'] = $msgPwd;
        }

		if ($buyMenuPosition == null) {
			$data['buyMenuPosition'] = NULL;
		} else {
			$data['buyMenuPosition'] = $buyMenuPosition;
		}

		if ($buyMenuName == null) {
			$data['buyMenuName'] = NULL;
		} else {
			$data['buyMenuName'] = $buyMenuName;
		}

		if ($buyMenuUrl == null) {
			$data['buyMenuUrl'] = NULL;
		} else {
			$data['buyMenuUrl'] = $buyMenuUrl;
		}
        $data['vendorLimit'] = $vendorLimit;
		$data['updateTime'] = date('Y-m-d H:i:s');

        $condition['customerId'] = array('eq', $cid);
        $setting = $CustomerSuperSettingModel->where($condition)->find();
        //孟慧增加log，并增加系统信息查询条件20180124
        $where_user['customerId'] = $cid;
        $where_user['agent'] = 'business';
        $where_user['status'] = 'open';
        $userName = $user->where($where_user)->getField('loginName');
        if ($setting) {
            $result = $CustomerSuperSettingModel->where($condition)->save($data);
            if ($result !== false) {
                R('Log/add', array('accountManage', module_id_accountManage, '账号管理', op_add, $CustomerSuperSettingModel->getLastSql(), '修改用户'.$userName.'账号设置'));
                Output::instance()->resultCode(code_success, "配置成功");
            } else {
                Output::instance()->resultCode(code_sql_error, '数据保存失败');
            }

		}else{
			$data['customerId'] = $cid;

			$result = $CustomerSuperSettingModel->add($data);

            if ($result) {
                R('Log/add', array('accountManage', module_id_accountManage, '账号管理', op_update, $CustomerSuperSettingModel->getLastSql(), '修改用户'.$userName.'账号设置'));
                Output::instance()->resultCode(code_success, "配置成功");
            } else {
                Output::instance()->resultCode(code_sql_error, '数据保存失败');
            }

		}
	}

    public function updateCustomerSms($cid, $cardId, $cardPwd)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

		SmsClient::chargeUp($cardId, $cardPwd);
		/*
		Session::switchCustomer(0);


		$CustomerSuperSettingModel = D('customer_super_setting');

		$condition['customerId'] = array('eq',$cid);
		$setting = $CustomerSuperSettingModel->where($condition)->find();


		$dataSetting['updateTime'] = date('Y-m-d H:i:s');
		if ($setting) {
			if ($setting["msgPointAvailable"] != NULL) {
				$dataSetting["msgPointAvailable"] = $setting["msgPointAvailable"] + $point;
			} else {
				$dataSetting["msgPointAvailable"] = $point;
				$dataSetting["msgPointUsed"] = 0;
			}
			$result = $CustomerSuperSettingModel->where($condition)->save($dataSetting);
		} else {
			$dataSetting['customerId'] = $cid;
			$dataSetting["msgPointAvailable"] = $point;
			$dataSetting["msgPointUsed"] = 0;
			$result = $CustomerSuperSettingModel->add($dataSetting);
		}

		if ($result !== false) {
			$SmsHistoryModel = M("sms_pay_history");
			$data["fromCustomerId"] = $cid;
			$data["point"] = $point;
			$data["createTime"] = date("Y-m-d H:i:s");
			$SmsHistoryModel->add($data);
			$msg["msgPointAvailable"] = $dataSetting["msgPointAvailable"];
			$msg["msgPointUsed"] = $setting["msgPointUsed"] == NULL ? 0 : $setting["msgPointUsed"] ;
			Output::instance()->object($msg);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}

		Session::switchCustomer($customerId);
		*/
	}

	public function getCustomerSmsMsg($cid, $order = "createTime", $orderBy = "desc", $start = 0, $limit = 25) {
		$SmsModel = D('sms_msg');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$where["fromCustomerId"] = $cid;
		$arr = $SmsModel->where($where)->order("$order $orderBy")->limit("$start, $limit")->select();
		if ($arr) {
			$total = $SmsModel->where($where)->count();
			Output::instance()->objArray($arr, $total);
		} else {
			Output::instance()->resultCode();
		}
	}

	public function getCustomerSmsUsed($cid, $startDate = '', $endDate = '') {
		$SmsModel = D('sms_msg');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$where["fromCustomerId"] = $cid;
		if ($startDate != '' && $endDate != '') {
			$where['createTime'] = array('between', array($startDate, $endDate));
		} else if ($startDate != '') {
			$where["createTime"] = array('egt', $startDate);
		} else if ($endDate != '') {
			$where["createTime"] = array('elt', $endDate);
		}

		$result["point"] = $SmsModel->where($where)->count("point");
		Output::instance()->object($result);
	}

    public function getUserSuperSettingById($cid)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

		$result = $this->getSuperSettingById($cid);
		if (!$result) {
			return;
		}

		$msgPointAvailable = SmsClient::getBalanceValue($result);
		if (!$msgPointAvailable) {
			$msgPointAvailable = 0;
		}
		$result["msgPointAvailable"] = $msgPointAvailable;

		Output::instance()->object($result);
	}

    public function getSuperSettingById($cid)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerSuperSettingModel = D('customer_super_setting');
		$condition['customerId'] = array('eq',$cid);
		$result = $CustomerSuperSettingModel->where($condition)->find();
		Session::switchCustomer($customerId);
		if (!$result) {
			Output::instance()->resultCode(code_sql_error);
			return;
		}
		return $result;
	}

	public function getSuperSetting() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$cid = Session::$user["customerId"];
		$result = $this->getSuperSettingById($cid);
		if (!$result) {
			return;
		}

		Output::instance()->object($result);
	}

	public function getSmsPayHistory($cid, $order = "createTime", $orderBy = "desc", $start = 0, $limit = 25) {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerSuperSettingModel = D('sms_pay_history');
		$condition['fromCustomerId'] = array('eq',$cid);
		$arr = $CustomerSuperSettingModel->where($condition)->order("$order $orderBy")->limit("$start, $limit")->select();

		Session::switchCustomer($customerId);
		if ($arr) {
			$total = $CustomerSuperSettingModel->where($condition)->count();
			Output::instance()->objArray($arr, $total);
		} else {
			Output::instance()->resultCode();
		}
	}

	/**
	 * 页面获取支付方式和物流方式列表
	 * @param int $cid
	 */
	public function getUserPayAndLogisticsList($cid){
		$CustomerSuperSettingModel = D('customer_super_setting');
		$condition['customerId'] = array('eq',$cid);
		$condition['deleted'] = array('eq', 0);
		$setting = $CustomerSuperSettingModel->where($condition)->find();

		if (!isset($setting)) {
			return;
		}
		$result = array();

		if($setting['allowPickUp'] || $setting['allowDelivery']){
			$logistics = array();
			if($setting['allowPickUp']){
				$pickup["text"] = ORDER_DELIVERYTYPE_PICKUP_TEXT;
				$pickup["value"] = ORDER_DELIVERYTYPE_PICKUP;
				array_push($logistics, $pickup);
			}
			if($setting['allowDelivery']){
				$logisticsCostModel = D('customer_logistics_cost');
				$where['customerId'] = $cid;
				$where['deleted'] = 0;
				$costList = $logisticsCostModel->where($where)->select();
				if ($costList !== false) {
					foreach($costList as $cost) {
						$delivery["text"] = $cost["logistics"];
						$delivery["value"] = ORDER_DELIVERYTYPE_DELIVERY . $cost["id"];
						$delivery["cost"] = $cost["cost"];
						$delivery["points"] = $cost["points"];
						array_push($logistics, $delivery);
					}
				}
			}
			$result['shipping'] = $logistics;
		}

		if($setting['allowWXPay'] || $setting['allowAlipay'] || $setting['allowDeliveryPay'] ||
				 $setting['allowStored'] || $setting['allowTransfer'] || $setting['allowUPay']){
			$pay = array();
			if($setting['allowWXPay']){
				$wxPay["text"] = ORDER_PAYTYPE_WXPAY_TEXT;
				$wxPay["value"] = ORDER_PAYTYPE_WXPAY;
				array_push($pay, $wxPay);
			}
			if($setting['allowAlipay']){
				$aliPay["text"] = ORDER_PAYTYPE_ALIPAY_TEXT;
				$aliPay["value"] = ORDER_PAYTYPE_ALIPAY;
				array_push($pay, $aliPay);
			}
			if($setting['allowDeliveryPay']){
				$delieveryPay["text"] = ORDER_PAYTYPE_DELIVERIY_PAY_TEXT;
				$delieveryPay["value"] = ORDER_PAYTYPE_DELIVERIY_PAY;
				array_push($pay, $delieveryPay);
			}
			if($setting['allowStored']){
				$storedPay["text"] = ORDER_PAYTYPE_STORED_PAY_TEXT;
				$storedPay["value"] = ORDER_PAYTYPE_STORED_PAY;
				array_push($pay, $storedPay);
			}
			if($setting['allowTransfer']){
				$transferPay["text"] = ORDER_PAYTYPE_TRANSFER_TEXT;
				$transferPay["value"] = ORDER_PAYTYPE_TRANSFER;
				array_push($pay, $transferPay);
			}
			if($setting['allowUPay']){
				$uPay["text"] = ORDER_PAYTYPE_UPAY_TEXT;
				$uPay["value"] = ORDER_PAYTYPE_UPAY;
				array_push($pay, $uPay);
			}
			$result['payType'] = $pay;
		}
		return $result;
	}


	// 管理员更新注册设置
	public function updateRegisterSetting(
			$agreementWebPageId = NULL,$agreementWebPageName = NULL,$agreementContent=NULL,
			$successWebPageId=NULL,$successWebPageName=NULL,$successContent=NULL,
			$smsMsg = NULL,
			$smsSendInterval = 60,
			$smsValidInterval= NULL,
			$agreementChannelWebPageId = NULL,
			$agreementChannelWebPageName = NULL,
			$agreementChannelContent = NULL,
			$agreementSupplierWebPageId = NULL,
			$agreementSupplierWebPageName = NULL,
			$agreementSupplierContent = NULL
			) {

		$RegisterSettingModel = D('customer_register_setting');

		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}


		$data['agreementChannelWebPageId'] = $agreementChannelWebPageId==NULL ?NULL:$agreementChannelWebPageId;
		$data['agreementChannelWebPageName'] = $agreementChannelWebPageName==NULL ?NULL:$agreementChannelWebPageName;
		$data['agreementChannelContent'] = $agreementChannelContent==NULL ?NULL:$agreementChannelContent;
		$data['agreementSupplierWebPageId'] = $agreementSupplierWebPageId==NULL ?NULL:$agreementSupplierWebPageId;
		$data['agreementSupplierWebPageName'] = $agreementSupplierWebPageName==NULL ?NULL:$agreementSupplierWebPageName;
		$data['agreementSupplierContent'] = $agreementSupplierContent==NULL ?NULL:$agreementSupplierContent;

		if($agreementWebPageId == NULL){
			$data['agreementWebPageId'] = NULL;
		}else{
			$data['agreementWebPageId'] = $agreementWebPageId;
		}

		if($agreementWebPageName == NULL){
			$data['agreementWebPageName'] = NULL;
		}else{
			$data['agreementWebPageName'] = $agreementWebPageName;
		}

		if($agreementContent == NULL){
			$data['agreementContent'] = NULL;
		}else{
			$data['agreementContent'] = $agreementContent;
		}

		if($successWebPageId == NULL){
			$data['successWebPageId'] = NULL;
		}else{
			$data['successWebPageId'] = $successWebPageId;
		}

		if($successWebPageName == null){
			$data['successWebPageName'] = NULL;
		}else{
			$data['successWebPageName'] = $successWebPageName;
		}

		if($successContent == NULL){
			$data['successContent'] = NULL;
		}else{
			$data['successContent'] = $successContent;
		}

		$data['smsMsg'] = $smsMsg;

		if ($smsSendInterval == NULL) {
			$data['smsSendInterval'] = NULL;
		} else {
			$data['smsSendInterval'] = $smsSendInterval;
		}

		if ($smsValidInterval == NULL) {
			$data['smsValidInterval'] = NULL;
		} else {
			$data['smsValidInterval'] = $smsValidInterval;
		}

		$data['updateTime'] = date('Y-m-d H:i:s');


// 		$condition['customerId'] = array('eq',$cid);
		$setting = $RegisterSettingModel->limit("0,1")->find();

		if($setting){
			$condition['id'] = array('eq',$setting['id']);

			$result = $RegisterSettingModel->where($condition)->save($data);

			if($result !== false){
				Output::instance()->resultCode(code_success,"配置成功");
			}else{
				Output::instance()->resultCode(code_sql_error,'数据保存失败');
			}

		}else{

			$result = $RegisterSettingModel->add($data);

			if($result){
				Output::instance()->resultCode(code_success,"配置成功");
			}else{
				Output::instance()->resultCode(code_sql_error,'数据保存失败');
			}
		}

	}

	public function getRegisterSettingByCId() {
		$RegisterSettingModel = D('customer_register_setting');
// 		$retVal = Session::init();
// 		if (!$retVal) {
// 			Output::instance()->resultCode(code_access_denied);
// 			return;
// 		}

		$setting = $RegisterSettingModel->limit("0,1")->find();

		if($setting){
			Output::instance()->object($setting);
		}else{
			Output::instance()->resultCode(code_sql_error);
		}
	}

	public function getRegisterSettingValue() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);
		$RegisterSettingModel = D('customer_register_setting');
		$setting = $RegisterSettingModel->find();

		Session::switchCustomer($customerId);
		return $setting;
	}


	public function getSupplierRegisterSetting() {
		$RegisterSettingModel = D('customer_register_setting');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$content = $RegisterSettingModel->field('agreementSupplierContent')->find();
		if($content){
			Output::instance()->object($content);
		}else{
			Output::instance()->resultCode();
		}
	}

	public function getChannelRegisterSetting() {
		$RegisterSettingModel = D('customer_register_setting');
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$content = $RegisterSettingModel->field('agreementChannelContent')->find();
		if($content){
			Output::instance()->object($content);
		}else{
			Output::instance()->resultCode();
		}
	}
	
	
	public function getMallSetting() {
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		/** 注意, 这里抽离一个特殊的内部, 因为需要做一个同样的方法, 但是不需要上面的验证, 目的为了BoluopaiAction接口 */
		return $this->getMallSettingDetail();
	}
    public function getMallSettingCopyForBoluopai() {

        /** 注意, 这里抽离一个特殊的内部, 因为需要做一个同样的方法, 但是不需要上面的验证, 目的为了BoluopaiAction接口 */
        return $this->getMallSettingDetail();
    }

	protected function getMallSettingDetail()
    {

        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $MallSetting = M("customer_mall_setting");
        $where['customerId']=$customerId;
        $setting = $MallSetting->where($where)->find();
        Session::switchCustomer($customerId);
        if (!$setting) {
            Log::write($MallSetting->getLastSql());
            Output::instance()->resultCode(code_mall_setting_not_found);
            return;
        }
        if ($setting["isOld"]) {
            if (empty($setting["appId"]) || empty($setting["appSecret"]) || empty($setting["paySignKey"])
                || empty($setting["partnerId"]) || empty($setting["partnerKey"])) {
                Output::instance()->resultCode(code_mall_setting_invalid);
                return;
            }
        } else {
            if (empty($setting["appId"]) || empty($setting["payKey"]) || empty($setting["mchId"])) {
                Output::instance()->resultCode(code_mall_setting_invalid);
                return;
            }
        }
        return $setting;
    }

	/**
	 * 返回运营管理员operate用户列表
	 *
	 */
	public function getOperateUserList($loginName='',$status='',$fullName='',$order="registered", $orderBy="desc", $start=0, $limit=25){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');

		$condition['agent'] = array('eq',"operate");
		!empty($fullName) ? $condition['fullName'] = array('like','%'.$fullName.'%'):'';
		!empty($loginName) ? $condition['loginName'] = array('like','%'.$loginName.'%'):'';
		!empty($status) ? $condition['status'] = array('eq',$status):'';
		$arr = $CustomerUser->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
		//echo $CustomerUser->getLastSql();
		$count = $CustomerUser->where($condition)->count();

		Session::switchCustomer($customerId);


		if($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success,"没有用户");
		}

	}

	/**
	 * 新增运营管理员
	 *
	 */
	public function addOperate($id){
		$entity = D("customer_user");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//$tradeTemplateArr = array();
		$arr = $entity->find($id);

		Output::instance()->object($arr);


	}




	/**
	 * 编辑运营管理员
	 */
	public function updateOperate($id){
		$entity = D("customer_user");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$entity->create();
		$time = date("Y-m-d H:i:s");
		if($id){
			 $entity->updateTime = $time;
        	 $result = $entity->where("id=$id")->save();
		}else {

			//校验登录名是否为唯一
			if($this->validateLoginName($entity->loginName)){
				return ;
			}
	   		 $entity->registered = $time;
			 $entity->agent = "operate";
			 $entity->password = Encryption::password($entity->password);
        	 $result = $entity->add();
		}
		Session::switchCustomer($customerId);
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}

	/**
	 * 校验登录名是否重复
	 * Enter description here ...
	 */
	private function validateLoginName($loginName){
		$entity = D("customer_user");
		$loginName = trim($loginName);
		$arry = $entity->where("loginName='$loginName'")->find();
		if(count($arry)>0){
			return true;
		}
		return false;
	}
	/**
	 * js校验返回数据
	 * @param unknown_type $loginName
	 */
	public function validateLoginNamePage($loginName){
		if($this->validateLoginName($loginName)){
			Output::instance()->resultCode(code_user_exist) ;
		}else{
			Output::instance()->resultCode(code_success) ;
		}
	}
	/**
	 * jquery validator校验返回数据
	 * @param unknown_type $loginName
	 */
	public function validateRegLoginName($loginName){
		if($this->validateLoginName($loginName)){
			Output::instance()->resultCode(false) ;
		}else{
			Output::instance()->resultCode(true) ;
		}
	}

	/**
	 * 获取分配账号信息
	 */

	public function getAccountList($id){

		$customerModel = D("customer");
		$customerUserModel = D("customer_user");
		$customerToUser = D("trade_customeruser_customer");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		//获取当前运行管理员账号分配的用户
		$customerUserModelSelectedArr = $customerUserModel->alias('cu')
		->field("cu.loginName,cu.id,cu.customerId as customerId")
		->join('wx_customer c on c.id = cu.customerId')
		->where("cu.agent='business' and cu.customerId in(select tcc.customerId from wx_trade_customeruser_customer tcc where tcc.customerUserId =$id  )")
		->select();




		//获取所有未分配的账号 会员agent：business

		$customerUserModelArr = $customerUserModel->alias('cu')
		->field("cu.loginName,cu.id,cu.customerId as customerId")
		->join('wx_customer c on c.id = cu.customerId')
		->where("cu.status = 'close' and cu.agent='business' and cu.customerId not in(select distinct(tcc.customerId) from wx_trade_customeruser_customer tcc )")
		->select();

		$result = array();
		$result["selectds"] = $customerUserModelSelectedArr;
		$result["noselectds"] = $customerUserModelArr;

		Output::instance()->objArray($result);

	}

	/**
	 * 为运营管理员分配工单
	 * @param unknown_type $id
	 * @param unknown_type $selectds
	 */
	public function updateAccountOrder($id,$selectds){

		$customerUser = D("customer_user");
		$customerToUser = D("trade_customeruser_customer");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerToUser->startTrans();
		$resultFlag = false;
		foreach ($selectds as $customerUserId){
			if($resultFlag){
				break ;
			}
			$customerToUser->customerUserId=$id;
			$customerToUser->customerId=$customerUserId;
			$result = $customerToUser->add();
			if(!$result){
				$resultFlag = true;
			}
		}

		if(!$resultFlag){
			$customerToUser->commit();
			//send email
			$this->sendEmailToOperate($selectds,$customerUser,$id,false);
		}else{
			$customerToUser->rollback();
		}

	}
	/**
	 * 取消分配的账号
	 * @param $id
	 * @param $selectds
	 */
	public function cancelAccountOrder($id,$selectds){
		$customerUser = D("customer_user");
		$customerToUser = D("trade_customeruser_customer");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerToUser->startTrans();
		$resultFlag = false;
		foreach ($selectds as $customerUserId){
			if($resultFlag){
				return ;
			}
			$result = $customerToUser->where("customerUserId = $id and customerId = $customerUserId")->delete();
			if(!$result){
				$resultFlag = true;
			}
		}

		if(!$resultFlag){
			$customerToUser->commit();
			$this->sendEmailToOperate($selectds,$customerUser,$id,true);
		}else{
			$customerToUser->rollback();
		}

	}

	/**
	 *分配和取消时，向平台运营管理员发送邮件
	 * @param $selectds
	 */
	private function sendEmailToOperate($selectds,$customerUser,$id,$isCanel){
			$customer_user = $customerUser->alias("cu")
			->field("cu.loginName,cu.email")
			->where("cu.id = $id")->find();
			if($customer_user){
				$sendEmailAddress = $customer_user["email"];
				$sendName = $customer_user["loginName"];
				//fenpeidezhanghao
				$userIds = implode(",", $selectds);
				$customerUsers = $customerUser->alias("cu")
				->field("cu.loginName")
				->where("cu.customerId in($userIds)")
				->select();
				if($customerUsers){
					$userNames = array();
					foreach($customerUsers as $entity){
						array_push($userNames,  $entity["loginName"]);
					}
					$userNameCount = count($userNames);
					$userNames = implode(",",$userNames);
					if(!$isCanel){
 						$title = "分配账号通知";
						$message = "<br>您好".$sendName."：<br>平台管理员为您分配了".$userNameCount."个账号，分别为".$userNames."。请尽快处理。谢谢！<br>";
					}else{
						$title = "取消分配账号通知";
						$message = "<br>您好".$sendName."：<br>平台管理员取消了分配给您的".$userNameCount."个账号，分别为".$userNames."。特此通知。谢谢！<br>";
					}
					//send email
					SendMail($sendEmailAddress,$message ,null,null);
				}

			}
	}

	/**
	 *
	 * 从选择的模板用户获取数据并导入新的用户中
	 * @param $customerTempId 引用模板用户的id
	 * @param $customerId 注册用户的id
	 */
	private function importDateToTemplate($customerTempId,$customerId){

		$arrayAll = array();
		$coustoerModuleGroupArray = array();
		//引用模板用户的id
		//$customerTempId = 1;
		//注册用户的id
		//$customerTempId= 2;

		//判定用户是否启用了文章管理//旧的是webPage
		$webPageArr = $this->getCustomerModuleGroup("articleManager", $customerTempId,"allow");
		if($webPageArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "articleManager");

			array_push($arrayAll, array($customerTempId."_web_page", "wx_".$customerId."_web_page"));
			array_push($arrayAll, array($customerTempId."_web_page_attachment", "wx_".$customerId."_web_page_attachment"));
			array_push($arrayAll, array($customerTempId."_web_page_tag", "wx_".$customerId."_web_page_tag"));
			array_push($arrayAll, array($customerTempId."_web_page_tag_list", "wx_".$customerId."_web_page_tag_list"));
		}

		//判断用户是否启用了产品功能。如果启用了同时开启订单功能，增加订单权限。
		$productArr = $this->getCustomerModuleGroup("product", $customerTempId,"allow");
		if($productArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "product");
			//创建表
			$sqlPath =module_sql_path("product");
			$cmgResult = self::userImportSQL($sqlPath,$customerId);
			if(!$cmgResult){
				//echo "创建产品模块相关表失败";
			}
			//导入数据
			array_push($arrayAll, array($customerTempId."_module_product_category", "wx_".$customerId."_module_product_category"));
			array_push($arrayAll, array($customerTempId."_module_product", "wx_".$customerId."_module_product"));
			array_push($arrayAll, array($customerTempId."_module_product_group", "wx_".$customerId."_module_product_group"));
			array_push($arrayAll, array($customerTempId."_module_product_specification_group", "wx_".$customerId."_module_product_specification_group"));
			array_push($arrayAll, array($customerTempId."_module_product_specification_name", "wx_".$customerId."_module_product_specification_name"));
			array_push($arrayAll, array($customerTempId."_module_product_specification", "wx_".$customerId."_module_product_specification"));
			array_push($arrayAll, array($customerTempId."_module_product_tag", "wx_".$customerId."_module_product_tag"));
			array_push($arrayAll, array($customerTempId."_module_product_tag_list", "wx_".$customerId."_module_product_tag_list"));
			array_push($arrayAll, array($customerTempId."_discount", "wx_".$customerId."_discount"));
			array_push($arrayAll, array($customerTempId."_discount_product", "wx_".$customerId."_discount_product"));
		}
		//判断用户是否启用了ftob。
		$ftobArr = $this->getCustomerModuleGroup("ftob", $customerTempId,"deny");
		$ftobTGManagerArr = $this->getCustomerModuleGroup("ftobTGManager", $customerTempId,"allow");
		$ftobDXManagerArr = $this->getCustomerModuleGroup("ftobDXManager", $customerTempId,"allow");
		/*
		if(($ftobArr&&!$ftobTGManagerArr&&!$ftobDXManagerArr)||(!$ftobArr&&$ftobTGManagerArr&&$ftobDXManagerArr)){
			//增加权限
			//array_push($coustoerModuleGroupArray, "ftob");
			//2014-12-2权限修改后的权限分配。如果用户启用了ftob  增加我要推广和我要代销
			 array_push($coustoerModuleGroupArray, "ftobTGManager");
			 array_push($coustoerModuleGroupArray, "ftobDXManager");
		}
		*/
		if(($ftobArr&&$ftobTGManagerArr)||(!$ftobArr&&$ftobTGManagerArr)){
			 array_push($coustoerModuleGroupArray, "ftobTGManager");
		}
		if($ftobArr&&$ftobDXManagerArr||(!$ftobArr&&$ftobDXManagerArr)){
			 array_push($coustoerModuleGroupArray, "ftobDXManager");
		}
		//判定用户是否启用了旧的微网站、消息互动
		$webSiteArr = $this->getCustomerModuleGroup("webSite", $customerTempId,"allow");
		if($webSiteArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "webSite");
			array_push($arrayAll, array($customerTempId."_material", "wx_".$customerId."_material"));
			array_push($arrayAll, array($customerTempId."_material_tags", "wx_".$customerId."_material_tags"));
			array_push($arrayAll, array($customerTempId."_material_keyword", "wx_".$customerId."_material_keyword"));
			array_push($arrayAll, array($customerTempId."_material_keyword_with_param", "wx_".$customerId."_material_keyword_with_param"));
		}
		//2014-12-2增加新的消息互动
		$materialManagerArr = $this->getCustomerModuleGroup("materialManager", $customerTempId,"allow");
		if($materialManagerArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "materialManager");
		}

		//判定用户是否启用了微商城,如果启用了同时开启订单功能，增加订单权限。
		$mallArr = $this->getCustomerModuleGroup("mall", $customerTempId,"allow");
		if($mallArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "mall");
			array_push($coustoerModuleGroupArray, "order");
			//如果没有启用微网站
			if(!$webSiteArr){
				array_push($arrayAll, array($customerTempId."_material", "wx_".$customerId."_material"));
				array_push($arrayAll, array($customerTempId."_material_tags", "wx_".$customerId."_material_tags"));
				array_push($arrayAll, array($customerTempId."_material_keyword", "wx_".$customerId."_material_keyword"));
				array_push($arrayAll, array($customerTempId."_material_keyword_with_param", "wx_".$customerId."_material_keyword_with_param"));
			}
		}


		//判定用户是否启用了动态微网站。
		$cmgArr = $this->getCustomerModuleGroup("dynamicWeb", $customerTempId,"allow");
		if($cmgArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "dynamicWeb");
			//创建表
			$sqlPath =module_sql_path("dynamicWeb");
			$cmgResult = self::userImportSQL($sqlPath,$customerId);
			if(!$cmgResult){
				//echo "创建动态微网站表字段失败";
			}
			//导入数据
			array_push($arrayAll, array($customerTempId."_module_dynamic_web", "wx_".$customerId."_module_dynamic_web"));
			array_push($arrayAll, array($customerTempId."_module_dynamic_web_page", "wx_".$customerId."_module_dynamic_web_page"));
			array_push($arrayAll, array($customerTempId."_module_dynamic_web_page_element", "wx_".$customerId."_module_dynamic_web_page_element"));
		}

		//判定用户是否启用了会员管理功能
		$memberArr = $this->getCustomerModuleGroup("member", $customerTempId,"allow");
		if($memberArr){
			//增加权限
			array_push($coustoerModuleGroupArray, "member");
			//创建表
			$sqlPath =module_sql_path("member");
			$cmgResult = self::userImportSQL($sqlPath,$customerId);
			if(!$cmgResult){
				//echo "创建会员模块相关表失败";
			}
			//导入数据
			//array_push($arrayAll, array($customerTempId."_member_category", "wx_".$customerId."_member_category"));
			array_push($arrayAll, array($customerTempId."_member_object", "wx_".$customerId."_member_object"));
			array_push($arrayAll, array($customerTempId."_member_object_base_info", "wx_".$customerId."_member_object_base_info"));
			array_push($arrayAll, array($customerTempId."_member_extend_information_column", "wx_".$customerId."_member_extend_information_column"));
			array_push($arrayAll, array($customerTempId."_member_extend_information_column_option", "wx_".$customerId."_member_extend_information_column_option"));
			array_push($arrayAll, array($customerTempId."_member_object_level", "wx_".$customerId."_member_object_level"));
			array_push($arrayAll, array($customerTempId."_member_object_level_privilege", "wx_".$customerId."_member_object_level_privilege"));
			array_push($arrayAll, array($customerTempId."_member_object_diy", "wx_".$customerId."_member_object_diy"));
		}
		//addAccessTags访问标签
		array_push($arrayAll, array($customerTempId."_access_tag", "wx_".$customerId."_access_tag"));
		//用户注册配置表,增加一条记录，在导入数据中进行操作//customer_super_setting
		if($coustoerModuleGroupArray){
			//导入数据，开通权限
			 $this->importDateCom($arrayAll,$coustoerModuleGroupArray,$customerTempId,$customerId);
		}else{
			//echo "no data";
		}


	}
	/**
	 * 获取用户权限
	 * @param unknown_type $module
	 * @param unknown_type $customerTempId
	 */
	private function getCustomerModuleGroup($module,$customerTempId,$permission){
		$customerModuleGroup = D("customer_module_group")->alias('cmg');
		$cmgArr = $customerModuleGroup
		->where("cmg.group = '$module' and cmg.permission = '".$permission."' and cmg.customerId = $customerTempId")
		->find();
		return $cmgArr;
	}

	/**
	 * 导入数据通用
	 * @param unknown_type $array
	 */
	private function importDateCom($array,$coustoerModuleGroupArray,$customerTempId,$customerId){
		$model = new Model();
        $model->startTrans();
		$flag=false;


		for ($i = 0; $i < count($array); $i++) {
			$object_old = M($array[$i][0]);
			$object = $object_old->select();
			if($object){
				if($flag){
					break ;
				}
				$wid = $model->table($array[$i][1])->addAll($object);
				if(!$wid){
					$flag = true;
				}
			}
		}
		if(!$flag){
			//加入权限
			if($coustoerModuleGroupArray){
				foreach ($coustoerModuleGroupArray as $entity) {
					if($flag){
						break ;
					}
					$data["customerId"]=$customerId;
					$data["group"]=$entity;
					$data["permission"]="allow";
					$cmgResults = $model->table("wx_customer_module_group")->add($data);
					if(!$cmgResults){
						$flag = true;
					}
				}
			}
		}
		if(!$flag){
			//customer_super_setting
			$customerSuperSettingMoldeArr = $model->table("wx_customer_super_setting")->where("customerId =$customerTempId")->find();
			if($customerSuperSettingMoldeArr){
				$customerSuperSettingMoldeArr["customerId"] = $customerId;
				$customerSuperSettingMoldeArr["id"] = null;
				$customerSuperSettingMoldeResult = $model->table("wx_customer_super_setting")->add($customerSuperSettingMoldeArr);
				if(!$customerSuperSettingMoldeResult){
					$flag = true;
				}
			}
		}
		if(!$flag){
			$model->commit();
			//echo "transaction scucess";
		}else{
			$model->rollback();
			//echo "transaction fail";
		}

	}


	/**
	 * 用户开启时导入sql文件
	 * @param unknown_type $sqlPath
	 * @param unknown_type $cid
	 */
	public static  function userImportSQL($sqlPath,$cid) {
		if(!file_exists($sqlPath)){
			//echo "数据库文件不存在。请添加在wx_api\Module\member下添加member.sql文件";
			return false;
		}

		// parse content
		$content = file_get_contents($sqlPath);
		$content = str_replace("\r","\n",$content);
		$sqls = array();
		$aSql = explode(";\n",trim($content));
		// get sqls
		$num = 0;
		foreach($aSql as $sql){
			$sqls[$num]='';
			$queries = explode("\n",$sql);
			$queries = array_filter($queries);
			foreach($queries as $query){
				$str1 = substr($query,0,1);
				if($str1!=='#' && $str1!=='-') $sqls[$num].=$query;
			}
			$num++;
		}
		unset($sql);
	   try {
			$model = new Model();
			//循环sql文件
			foreach($sqls as $sql){
			$sql = str_replace(C('ORIGINAL_DB_PREFIX'), C('DB_PREFIX').$cid."_", $sql);
			$model->query($sql);
			};
			return true;
	   } catch (Exception $e) {
				throw_exception("operator: ". $e->getMessage());
				return false;
		}

	}

	/**
	 * 修改密码（运营管理员）
	 * @param $id 运营管理员id
	 */
	public function updateOperatorPassword($id){
		$customerUser = D("customer_user");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerUser->create();
		$customerUser->password = Encryption::password($customerUser->password);
		$time = date("Y-m-d H:i:s");
		$customerUser->updateTime = $time;
		$userArr = $customerUser->alias("cu")
		//->where("cu.id = $id and cu.agent='operate'")
		->where("cu.id = $id")
		->save();
		if($userArr){
	 		Output::instance()->resultCode(code_success);
		}else{
			 Output::instance()->resultCode(code_sql_error);
		}

	}


	/**
	 * 2014-11-3前端注册页面，获取模板
	 */
	public function getTradeTemplates(){
		$tradeTemplate = D("trade_template");
		$tradeTemplateArr = $tradeTemplate->alias("tt")
		->field("tt.id,tt.name,tt.price,tt.description,tt.imgUrl")
		->where("tt.deleted='0' and tt.display='1'")
		->order("tt.serialNo asc")
		->select();

		Output::instance()->objArray($this->getTemplateDescriptionLength($tradeTemplateArr));
	}


	/**
	 * 前端注册页面。获取服务
	 */
	public function getTradeAppreciations(){
		$tradeAppreciation = D("trade_appreciation");
		$tradeAppreciationArr = $tradeAppreciation->alias("ta")
		->field("ta.id,ta.name,ta.price,ta.description,ta.imgUrl")
		->where("ta.deleted='0' and ta.display='1'")
		->order("ta.serialNo asc")
		->select();
		Output::instance()->objArray($this->getTemplateDescriptionLength($tradeAppreciationArr));
	}

	//处理模板和服务的描述信息
	private function getTemplateDescriptionLength($array){
		$extArr = array();
		//能被3 整除的长度
		$length = 65;
		for ($i = 0; $i < count($array); $i++) {
			$description =  trim(strip_tags($array[$i]["description"]),"");
			$description = str_replace(' ','',$description);
			$id = $tradeTemplateArr[$i]["id"];
			if(mb_strlen($description,"utf-8")>$length){
				$description = trim(mb_substr($description,0,$length,"utf-8"))."......";
			}
			$array[$i]["description"] = "<p>".$description."</p>";
			$extArr[$i] = $array[$i];
		}

		return $extArr;
	}
	private function getRegProductUrl($id,$url){
		$href = "<a href='".$url.$id."' class='xqtext'>查看详情</a>";
		return $href;
	}


	/**
	 * 获取模板或者服务的详细描述信息
	 * @param $id
	 * @param $isTemplate
	 */
	public function showRegProductInfo($id,$isTemplate){
		if("template"==$isTemplate){
			$tradeTemplate = D("trade_template");
			$result = $tradeTemplate->alias("tt")
			->field("tt.id,tt.description")
			->where("tt.deleted='0' and tt.display='1' and tt.id = $id")
			->find();
		}else{
			$tradeAppreciation = D("trade_appreciation");
			$result = $tradeAppreciation->alias("ta")
			->field("ta.id,ta.description")
			->where("ta.deleted='0' and ta.display='1' and ta.id = $id")
			->find();
		}

		Output::instance()->object($result);
	}

	/**
	 * 返回旅游用户列表
	 *
	 */
	public function getTourUserList($loginName='',$status='',$fullName='',$order="registered", $orderBy="desc", $start=0, $limit=25){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$CustomerUser = D('customer_user');
		//Log::write('getTourUserList 11111');
		//$condition['agent'] =array('eq',array('bussnessMng','productMng'),'OR');
		$condition=" (agent='bussnessMng' or agent='productMng') ";
		!empty($fullName) ? $condition=$condition." and fullName like '%$fullName%' ":"";
		!empty($loginName) ? $condition=$condition." and loginName like '%$loginName%' ":"";
		!empty($status) ? $condition=$condition." and status = '$status' ":"";

		$arr = $CustomerUser->where($condition)->order("$order $orderBy")->limit("$start,$limit")->select();
		//Log::write('getTourUserList 22222'.$CustomerUser->getLastSql());
		$count = $CustomerUser->where($condition)->count();

		Session::switchCustomer($customerId);


		if($arr) {
			Output::instance()->objArray($arr,$count);
		} else {
			Output::instance()->resultCode(code_success,"没有用户");
		}
	}

	/**
	 * 编辑产品管理员、业务管理员
	 */
	public function updateTourUser($id){
		$entity = D("customer_user");
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$customerId = Session::$user["customerId"];
		Session::switchCustomer(0);

		$entity->create();
		$time = date("Y-m-d H:i:s");
		if($id){
			 $entity->updateTime = $time;
        	 $result = $entity->where("id=$id")->save();
		}else {

			//校验登录名是否为唯一
			if($this->validateLoginName($entity->loginName)){
				return ;
			}
			 $entity->customerId=$customerId;
	   		 $entity->registered = $time;
			 $entity->password = Encryption::password($entity->password);
        	 $result = $entity->add();
		}
		Session::switchCustomer($customerId);
		if ($result) {
			Output::instance()->resultCode(code_success);
		} else {
			Output::instance()->resultCode(code_sql_error);
		}
	}


	public function getUserSession() {
	  $retVal = Session::init();
	  if (!$retVal) {
	    Output::instance()->resultCode(code_access_denied);
	    return;
	  }

	  Output::instance()->object(Session::$user);
	}

    /**
     * 判断用户是否有绑定二维码登录权限
     * @param int $status 是判断运营用户是绑定还是解绑二维码登录（0：解绑，1：绑定）
     * @param int $method 用户解绑方式（0：滑动按钮解绑，1：扫描二维码解绑）
     */
    public function bindQRcodePower($status, $method = 0)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }


        /**2.数据库模型*/
        $userId = session::$user['id'];
        $customerId = session::$user['customerId'];
        Session::switchCustomer(0);
        $customer = M('customer');
        $user = M('customer_user');
        $bind = M('qrcode_bind');
        $unbind = M('qrcode_unbind');
        Session::switchCustomer($customerId);


        /**3.逻辑处理，数据返回*/
        //根据status状态判断运营用户是绑定还是解绑二维码
        $time = date('Y-m-d H:i:s', time());
        if ($status == 1) {
            $customerInfo = $customer->field('qrcodeLogin')->where("id=$customerId")->find();
            //判断用户所属平台是否开启二维码登录
            if ($customerInfo['qrcodeLogin']) {
                $data = QRCode::add($userId . "_绑定二维码登录_" . '_' . $time, null, "qrcode", '', "bindQRcodeLogin", QR_SCENE, '', '', $customerId);
                if ($data) {
                    $bind->create();
                    $bind->ticket = $data['ticket'];
                    $bind->userId = $userId;
                    $bind->customerId = $customerId;
                    $bind->createTime = date('Y-m-d H:i:s', time());
                    $bind->add();
                    $img = $data["img"];
                    $return['code'] = 0;
                    $return['msg'] = $img;
                    $return['ticket'] = $data['ticket'];
                    Output::instance()->object($return);
                } else {
                    $return['code'] = 1;
                    $return['msg'] = '生成绑定二维码失败请重试';
                    Output::instance()->object($return);
                }
            } else {
                $return['code'] = 2;
                $return['msg'] = '您所属平台没有开启二维码登录权限';
                Output::instance()->object($return);
            }

        } else {
            if ($method == 0) {
                $data['uopenId'] = '';
                $result = $user->where("id=$userId")->save($data);
                if ($result !== false) {
                    $content_sql = $user->getLastSql();
                    R('Log/add', array('accountSetting', '132', '账号设置', op_update, $content_sql, '解绑微信扫码登录'));
                    $return['code'] = 0;
                    $return['msg'] = '恭喜您解绑成功';
                    Output::instance()->object($return);
                } else {
                    $return['code'] = 1;
                    $return['msg'] = '解绑失败请重试';
                    Output::instance()->object($return);
                }
            } else if ($method == 1) {
                $data = QRCode::add($userId . "_扫描二维码解绑微信_" . $time, null, "qrcode", '', "qrcodeUnbind", QR_SCENE, '', '', $customerId);
                if ($data) {
                    $unbind->create();
                    $unbind->ticket = $data['ticket'];
                    $unbind->userId = $userId;
                    $unbind->customerId = $customerId;
                    $unbind->createTime = date('Y-m-d H:i:s', time());
                    $unbind->add();
                    $img = $data["img"];
                    $return['code'] = 0;
                    $return['msg'] = $img;
                    $return['ticket'] = $data['ticket'];
                    Output::instance()->object($return);
                } else {
                    $return['code'] = 1;
                    $return['msg'] = '生成解绑二维码失败请重试';
                    Output::instance()->object($return);
                }

            }

        }

    }

    //判断二维码登陆是否成功,需要customerId和ticket
    public function judgeQRcodeLogin($cid, $ticket)
    {
        /**1.参数获取*/
        $customerId = $cid;
        $ticket = $ticket;

        /**2.数据表模型*/
        Session::switchCustomer(0);
        $login = M('qrcode_login');
        $customer_user = M('customer_user');
        $role = M('customer_user_role');
        Session::switchCustomer($customerId);

        /**3.筛选条件*/
        $where['customerId'] = array("eq", $customerId);
        $where['ticket'] = array("eq", $ticket);

        /**4.数据查询*/
        $user = $login->field('success,userId')->where($where)->find();
        $userId = $user['userId'];


        /**5.数据返回*/
        //判断用户扫码之后是否登录成功
        if ($user['success'] == 1) {
            $map['cu.id'] = array('eq', $userId);
            $map['activationKey'] = array('exp', ' is NULL');
            $user = $customer_user->alias('cu')->where($map)
                ->join('wx_customer c on c.id = cu.customerId')
                ->join('wx_customer_weixin_profile b on c.id=b.cid')
                ->field("cu.*,c.role,c.isApiAuth,c.appid,c.mode,b.grantStatus")->find();
            if (!isset($user)) {
                Output::instance()->resultCode(code_user_not_exist);
                return;
            } else if (strcasecmp($user['status'], 'open') != 0) {
                Output::instance()->resultCode(code_user_status_invalid);
                return;
            }
            $agent = '';
            $agentId = '';

            /** 处理角色英文名 */
            $arr_Role = $role
                ->alias('cur')
                ->join('wx_role r ON r.id = cur.roleId')
                ->where(['userId' => $userId])
                ->field('roleId, englishRole')
                ->select();

            $arr_roleId = array_filter(array_column($arr_Role, 'roleId'));  // 去除数组中的空值
            $arr_englishRole = array_filter(array_column($arr_Role, 'englishRole'));

            if (!$arr_roleId || !$arr_englishRole) {    // 如果没有角色, 报错
                Output::instance()->resultCode(code_sql_error);
                return;
            }
            $agentId = implode(',', $arr_roleId);
            $agent = implode(',', $arr_englishRole);
            $user['agentId'] = $agentId;
            $user['agent'] = $agent;
            $session = Session::setCurrentUser($user);

            $result = new stdClass();
            $result->fullName = $user['fullName'];
            $result->agent = $user['agent'];
            $result->agentId = $user['agentId'];
            $result->customerId = $user['customerId'];
            $result->userId = $user['id'];
            $result->status = $user['status'];
            $result->mode = $user['mode'];
            $result->grantStatus = $user['grantStatus'];
            $result->role = $user['role'];
            $result->appid = $user['appid'];
            $result->session_id = $session->session_id;
            Output::instance()->object($result);

        } else if ($user['success'] == 2) {
            $return['code'] = 1;
            $return['msg'] = '二维码登录失败';
            Output::instance()->object($return);
        }

    }

    //判断绑定是否成功的接口
    public function judgeBindSuccess($ticket, $type = NULL)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        $bind = M('qrcode_bind');
        Session::switchCustomer($customerId);
        $weixin = M("user_weixin_info");

        /**3.数据查询*/
        $uopenId = $user->field('uopenId')->where("id=$userId")->find();
        $bindId = $bind->field('id,success')->where("ticket='$ticket'")->find();

        /**4.数据返回*/
        if ($uopenId['uopenId'] && ($bindId['success'] == 1)) {
            $content_sql = $user->getLastSql();
            R('Log/add', array('accountSetting', '132', '账号设置', op_update, $content_sql, '绑定微信扫码登录'));
            if ($type == 'gg') {
                R("GgGrade/dealBindGrade",array('bindWeixin'));
            }
           $weixinInfo =  $weixin->field('headimgurl,nickname')->where("openid=".$uopenId['uopenId'] )->find();
            $return['code'] = 0;
            $return['msg'] = '恭喜您绑定成功';
            $return['data'] = [
              'headimgurl'=> $weixinInfo['headimgurl'],
              'nickname'=> $weixinInfo['nickname']
            ];
            Output::instance()->object($return);
        } else if ($bindId['success'] == 2) {
            $return['code'] = 1;
            $return['msg'] = '绑定失败请重试';
            Output::instance()->object($return);
        } else if ($bindId['success'] == 3) {
            $return['code'] = 2;
            $return['msg'] = '您已绑定成功法无需重新绑定';
            Output::instance()->object($return);
        } else if ($bindId['success'] == 4) {
            $return['code'] = 2;
            $return['msg'] = '此微信已经绑定其他账号，不可重复绑定';
            Output::instance()->object($return);
        }
    }

    //判断解绑是否成功的接口
    public function judgeUnbindSuccess($ticket, $type = NULL)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        $unbind = M('qrcode_unbind');
        Session::switchCustomer($customerId);

        /**3.数据查询*/
        $unbindId = $unbind->field('id,success')->where("ticket='$ticket'")->find();

        /**4.数据返回*/
        if ($unbindId['success'] == 1) {
            R('Log/add', array('accountSetting', '132', '账号设置', op_update, $unbind->getLastSql(), '解绑微信'));
            $return['code'] = 0;
            $return['msg'] = '恭喜您解绑成功';
            Output::instance()->object($return);
        } else if ($unbindId['success'] == 2) {
            $return['code'] = 1;
            $return['msg'] = '解绑失败请重试';
            Output::instance()->object($return);
        } else if ($unbindId['success'] == 3) {
            $return['code'] = 2;
            $return['msg'] = '您不是此账号绑定者，无权解绑此账号';
            Output::instance()->object($return);
        } else if ($unbindId['success'] == 4) {
            $return['code'] = 2;
            $return['msg'] = '您之前未绑定无需解绑';
            Output::instance()->object($return);
        }
    }

    public function updatePassword($password, $newPassword)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $pwd = Encryption::password($password);
        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        Session::switchCustomer($customerId);
        $where['id'] = array('eq', $userId);
        $where['password'] = array('eq', $pwd);
        $arr = $user->where($where)->find();
        if (!empty($arr)) {
            $data['password'] = Encryption::password($newPassword);;
            $result = $user->where($where)->save($data);
            if ($result) {
                Output::instance()->resultCode(code_success);
            } else {
                Output::instance()->resultCode(code_sql_error);
            }
        } else {
            $return['code'] = 1;
            $return['msg'] = '修改密码失败,原密码不正确';
            Output::instance()->object($return);
        }
    }

    /**
     * 判断用户之前是否绑定
     * @param $status 判断请求的场景，默认为进入系统的时候进行判断，2：页面内的判断
     */
    public function getQRcodeBindStatus($status = 1)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        $customer = M('customer');
        Session::switchCustomer($customerId);


        /**3.数据获取*/
        $userInfo = $user->field('uopenId,bindNotice')->where("id=$userId")->find();
        $customerInfo = $customer->field('qrcodeLogin')->where("id=$customerId")->find();
        //进入页面的时候判断一下是否需要弹窗提醒
        if ($status == 1) {
            if ($userInfo['bindNotice']) {
                $return['code'] = 5;
                $return['msg'] = '用户关闭绑定提示';
                Output::instance()->object($return);
            } else {
                if ($customerInfo['qrcodeLogin']) {
                    if ($userInfo['uopenId']) {
                        $return['code'] = 4;
                        $return['msg'] = '已绑定';
                        Output::instance()->object($return);
                    } else {
                        R('CUser/bindQRcodePower', array(1));  //0:返回二维码等信息
                    }
                } else {
                    $return['code'] = 2;
                    $return['msg'] = '平台已关闭二维码登录功能';
                    Output::instance()->object($return);
                }
            }
        } else {
            if ($customerInfo['qrcodeLogin']) {
                if ($userInfo['uopenId']) {
                    $return['code'] = 4;
                    $return['msg'] = '已绑定';
                    Output::instance()->object($return);
                } else {
                    $return['code'] = 0;
                    $return['msg'] = '未绑定';
                    Output::instance()->object($return);

                }
            } else {
                $return['code'] = 2;
                $return['msg'] = '平台已关闭二维码登录功能';
                Output::instance()->object($return);
            }
        }


    }

    /**
     * 用户关闭进入系统的绑定弹窗提醒
     */
    public function closeBindNotice()
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        Session::switchCustomer($customerId);

        /**3.数据的保存*/
        $data['bindNotice'] = 1;
        $result = $user->where("id=$userId")->save($data);

        /**4.判断保存结果*/
        if ($result !== false) {
            $return['code'] = 0;
            $return['msg'] = 'ok';
            Output::instance()->object($return);
        } else {
            $return['code'] = 1;
            $return['msg'] = '保存不再提醒失败,请重试';
            Output::instance()->object($return);
        }

    }


    //需要平台的cid
    public function qrcodeRegister($cid)
    {
        //此功能是为了让稿稿以外的平台可以使用这个功能
        $customerId = $cid;
        /**1.数据表模型*/
        Session::switchCustomer(0);
        $user = M('customer_user');
        $register = M('qrcode_register');
        Session::switchCustomer($customerId);
        $time = date('Y-m-d H:i:s');
        $data = QRCode::add($customerId . "_用户注册_" . $time, null, "qrcode", '', "register", QR_SCENE, '', '', $customerId);
        if ($data['code']) {
            return;
            // $return['code'] = 1;
            // $return['msg'] = '生成登录二维码失败请重试';
            // Output::instance()->object($return);
        } else {
            $register->create();
            $register->ticket = $data['ticket'];
            $register->customerId = $customerId;
            $register->add();
            $img = $data["img"];
            $return['code'] = 0;
            $return['msg'] = $img;
            $return['data'] = $data['ticket'];
            Output::instance()->object($return);
        }

    }


    //判断二维码登陆是否成功,需要customerId和ticket
    public function judgeQRcodeRegister($cid, $ticket)
    {
        /**1.参数获取*/
        $customerId = $cid;
        $ticket = $ticket;

        /**2.数据表模型*/
        Session::switchCustomer(0);
        $register = M('qrcode_register');
        $customer_user = M('customer_user');
        $gg_user = M('gg_user');
        $qrcode = M('qrcode');
        Session::switchCustomer($customerId);

        /**3.筛选条件*/
        $where['customerId'] = array("eq", $customerId);
        $where['ticket'] = array("eq", $ticket);

        /**4.数据查询*/
        $qrcodeInfo = $qrcode->field('fromCustomerId, name')->where("ticket='$ticket'")->find();
        $userInfo = $register->field('success,userId, openId')->where($where)->find();
        $userId = $userInfo['userId'];


        /**5.数据返回*/
        //判断用户扫码之后是否注册成功
        if ($userInfo['success'] == 1) {
            R('Gg/wx_initUser', array($userId));
            R('Log/add', array('accountSetting', '132', '账号设置', op_update, $register->getLastSql(), '微信扫码注册成功'));

            $return['code'] = 0;
            $return['msg'] = 'ok';
            $return['data'] = $userId;
            Output::instance()->object($return);

        } else if ($userInfo['success'] == 2) {
            $return['code'] = 1;
            $return['msg'] = '二维码注册失败';
            Output::instance()->object($return);
        } else if ($userInfo['success'] == 3) {
            $person = $customer_user->where("id=$userId")->find();
            //$person['renzheng'] = $person['status'];
            $ggperson = $gg_user->where("cuid={$person['id']}")->find();
            $person['renzheng'] = $ggperson['status'];
            $session = Session::setCurrentUser($person);
            $person['isComplete'] = $ggperson['isComplete'];
            $person['isreg'] = 2;
            $person['session_id'] = $session->session_id;
            $return['code'] = 2;
            $return['msg'] = '之前已注册，将直接为您返回登录信息';
            $return['data'] = $person;

            Output::instance()->object($return);
        }else if ($userInfo['success'] == 4){
            $return['code'] = 3;
            $return['msg'] = '此微信号已被绑定';
            Output::instance()->object($return);
            return ;
        }

    }

    //上传头像接口
    public function uploadHeadimg($url)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.数据表模型*/
        $customerId = Session::$user['customerId'];
//        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $user = M('customer_user');
        Session::switchCustomer($customerId);
        $arg['id'] = Session::$user['id'];

        $data['profileUrl'] = $url;
        $result = $user->where($arg)->save($data);

        if (is_numeric($result)) {
            $return['code'] = 0;
            $return['msg'] = '头像上传成功';
            $return['data'] = '';

            Output::instance()->object($return);
        } else {
            $return['code'] = 1;
            $return['msg'] = '头像上传失败请重试';
            $return['data'] = '';
            Output::instance()->object($return);
        }

    }

	/**
	 * 获取员工相关数据,绑定好友非销售源, 获取好友密友数据
	 * @param string $search      /组名/登录名/名称
	 * @param string $order         /排序
	 * @param string $by
	 * @param int $start            /分页
	 * @param int $limit
	 * @param boolean $flag        //员工列表导出   1 导出
	 */
	public function getEmployeeList($search='', $order='updateTime', $by='desc', $start=0, $limit=10,$vid=NULL,$flag=false){
		$retVal = Session::init();
		if(!$retVal){
			Output::instance()->resultCode(code_access_denied);
			return;
		}

		//获取和员工绑定的密友,作为销售源的数据, 如果非销售源就获取密友数据
		$userId = Session::$user['userId'];
		$id = Session::$user['id'];
		$agent = Session::$user['agent'];
		$cid = Session::$user['customerId'];
		Session::switchCustomer(0);
		$indMedia_tab = M('ind_media_info');
		$customerUser_tab = M('customer_user');
		$miuStatistics_tab = M('miu_statistics');
		$customerTagListModule = M('customer_tag_list');
		$saleStatistics_tab = M('salesource_statistics');
		$quan_user_tab = M('quan_user');
		Session::switchCustomer($cid);

		$where = [];
		$where['a.agent'] = 'service';
		$where['a.customerId'] = $cid;
		if($vid){
			$Vendors = R('Vendor/getMivendorChildList',array($vid,'string'));
			$where['a.vid'] = array('in', $Vendors);
		}else{
			if (!empty($agent) && Session::isVendor()){
				$vid  = $customerUser_tab->where(['id' => $id])->getField('vid');
				$Vendors = R('Vendor/getMivendorChildList',array($vid,'string'));
				$where['a.vid'] = array('in', $Vendors);
			}
		}

		if($search){
			$map['g.group_name']  = array('like', '%'.$search.'%');
			$map['a.loginName']  = array('like','%'.$search.'%');
			$map['a.fullName']  = array('like','%'.$search.'%');
			$map['_logic'] = 'or';
			$where['_complex'] = $map;
		}

		$mediaInfo = $indMedia_tab->where(['cid'=>$cid, 'deleted'=>0, 'isDefault'=>1])->find();

		//需要获取好友人数, 总的分享浏览次数, 订单数, 总销售额, 总收入, 账户余额
		$employeeList = $customerUser_tab->alias('a')
			->join('left join wx_'.$cid.'_user_weixin_info u on u.openid=a.openid')
			->join('left join wx_'.$cid.'_user_weixin_group g on g.group_id=a.groupId and g.mediaId='.$mediaInfo['id'])
			->join('left join wx_mivendor v on a.vid=v.id')
			->where($where)
			->field('a.id, a.loginName,a.phone,a.fullName,a.groupId, a.qid, g.group_name,a.storeId,
            a.storeName,u.userId as bindUserId, u.nickname as bindNickName,u.headimgurl as bindHeadImgUrl,v.id as vendorId,
            v.name as vendorName')
			->order('a.'.$order.' '.$by)
			->limit($start, $limit)
			->select();

		//新增查询所有列表  去除limit
		if($flag == 1)
		{
			$employeeList = $customerUser_tab->alias('a')
				->join('left join wx_'.$cid.'_user_weixin_info u on u.openid=a.openid')
				//->join('left join wx_quan_user q on q.uid=u.id and deleted=0')
				->join('left join wx_'.$cid.'_user_weixin_group g on g.group_id=a.groupId and g.mediaId='.$mediaInfo['id'])
				->join('left join wx_mivendor v on a.vid=v.id')
				->where($where)
				->field('a.id, a.loginName,a.phone,a.fullName,a.groupId, a.qid, g.group_name,a.storeId,
            a.storeName,u.userId as bindUserId, u.nickname as bindNickName,u.headimgurl as bindHeadImgUrl,v.id as vendorId,v.name as vendorName')
				->order('a.'.$order.' '.$by)
				->select();
		}
		//Log::write('jie-----123'.$customerUser_tab->getLastSql());
		    $total = $customerUser_tab->alias('a')
            ->join('left join wx_'.$cid.'_user_weixin_info u on u.openid=a.openid')
            ->join('left join wx_'.$cid.'_user_weixin_group g on g.group_id=a.groupId and g.mediaId='.$mediaInfo['id'])
            ->join('left join wx_mivendor v on a.vid=v.id')
            ->where($where)
            ->count();
		//var_dump($customerUser_tab->getLastSql());exit;
		if($employeeList == null){
			Output::instance()->object([
				'total'=>0,
				'results'=>[]
			]);
			return;
		}
		$result = [];
		foreach($employeeList as $k=>$v){
			$otherInfo = [];
			if($v['bindUserId']){
				$bool = $quan_user_tab->alias('a')
					->join('inner join wx_miyouquan m on a.qid=m.id')
					->where(['a.uid'=>$v['bindUserId'], 'm.cId'=>$cid, 'a.deleted'=>0])
					->field('a.isSaleSource,a.totalRevenue,a.miCoins')
					->find();
				//Log::write('jie-----222'.$quan_user_tab->getLastSql());
				if($bool){
					//是销售源
					$otherInfo = R('MiYouQuan/StatisData',array($cid, $v['qid'], $v['bindUserId'], 2));
//                    $otherInfo = $saleStatistics_tab->where(['uid'=>$v['bindUserId'], 'cid'=>$cid])->find();
					//Log::write('jie-----222'.$saleStatistics_tab->getLastSql());
				}/*else {
                    //密友主公
                    $otherInfo = $miuStatistics_tab->where(['uid'=>$v['bindUserId'],'cid'=>$cid])->find();
                    //Log::write('jie-----222'.$miuStatistics_tab->getLastSql());
                }*/
			}

			$tagInfo = $customerTagListModule->alias('a')->join('wx_customer_tag as b on a.tagId=b.id')->where(['a.uid'=>$v['id'],'a.cid'=>$cid])->field('group_concat(b.id) as tagId,group_concat(b.tagName) as tagName')->find();
			$v['tagId'] =$tagInfo['tagId'];
			$v['tagName'] =$tagInfo['tagName'];
			$v['friends'] = $otherInfo['friendCount']?$otherInfo['friendCount']:0;
			$v['friends'] = $otherInfo['friendCount']?$otherInfo['friendCount']:0;
			$v['shareUv'] = $otherInfo['shareUv']?$otherInfo['shareUv']:0;
			$v['orderCount'] = $otherInfo['buyOrderCount']?$otherInfo['buyOrderCount']:0;
			$v['salesAmount'] = $otherInfo['buyOrderPrice']?$otherInfo['buyOrderPrice']:0;
			$v['balance'] = $bool['miCoins']?$bool['miCoins']:0;
			$v['income'] = $bool['totalRevenue']?$bool['totalRevenue']:0;
			$result[$k] = $v;
		}

		if($flag == 1)
		{
			$data[0] = array(
				//'temp'              => "",
				//'bindNickName'     =>'员工微信',
				'loginName'      => '登录名',
				'fullName'      => '用户名',
				'phone'              => '手机号',
				'group_name' => '分组',
				'storeName'   => '所属门店',
				'friends'             => '好友数（人）',
				'shareUv'             => '分享总浏览数（人）',
				'orderCount'             => '订单数',
				'salesAmount'             => '总销售额（元）',
				'income'             => '总收入（元）',
				'balance'             => '账户余额（元）',

			);
			foreach ($result as $k1 => $v1) {
				if ($v1["code"]) {
					$v1["code"]    = '';
					$v1["company"] = '';
				}
				//$data[$k1+1]['temp']                = '';
				//$data[$k1+1]['bindNickName']        = $v1['bindNickName'];
				$data[$k1+1]['loginName']                = $v1['loginName'];
				$data[$k1+1]['fullName']                = $v1['fullName'];
				$data[$k1+1]['phone']   = $v1['phone'];
				$data[$k1+1]['group_name']     = $v1['group_name'];
				$data[$k1+1]['storeName']               = $v1['storeName'];
				$data[$k1+1]['friends']           = $v1['friends'];
				$data[$k1+1]['shareUv']           = $v1['shareUv'];
				$data[$k1+1]['orderCount']           = $v1['orderCount'];
				$data[$k1+1]['salesAmount']           = $v1['salesAmount'];
				$data[$k1+1]['income']           = $v1['income'];
				$data[$k1+1]['balance']           = $v1['balance'];
			}
			Output::instance()->objArrayExcel('员工信息'.date("Y-m-d H:i:s"), '', $data);
		} else {
			Output::instance()->object([
				'total'=>$total,
				'results'=>$result
			]);
		}

	}
	/**
     * 获取员工终端配置
     */
    public function getEmployeeCfg(){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $employeeCfg_tab = M('employee_terminal_config');
        Session::switchCustomer($cid);
        $result = $employeeCfg_tab->where('cId='.$cid)->find();
        $customer = WeixinApi::getCustomer();
        if($customer['mode']&&$customer['grantStatus']){
            $domainName = $customer["appid"];
            $domainNameRet="http://".$domainName.".".C('NEWSERVER_HOST');
        }else{
            $domainNameRet = C("SERVER_HOST");
        }
        if($result['menuJson']){
            $result['menuJson'] = json_decode($result['menuJson'], true);
        }
        if($result){
            Output::instance()->object([
               'code'=>0,
               'result'=>$result,
               'domainName'=>$domainNameRet
            ]);
            return;
        }
        Output::instance()->object([
            'code'=>-1,
            'result'=>[],
            'domainName'=>$domainNameRet
        ]);
    }

    /**
     * 员工终端配置
     * @param int $id   /id
     * @param string $themeImg    /主题图
     * @param string $backgroudImg  /背景图
     * @param string $menuJson  /菜单配置
     */
    public function saveEmployeeCfg($id='', $themeColor, $themeImg='', $homePageImg='', $menuJson=''){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $employeeCfg_tab = M('employee_terminal_config');
        Session::switchCustomer($cid);
        $data = [];
        $data['themeColor'] = $themeColor;
        $data['themeImg'] = $themeImg;
        $data['homePageImg'] = $homePageImg;
        $data['menuJson'] = $menuJson;
        $data['updateTime'] = date('Y-m-d H:i:s');
        //Log::write('jie------123'.print_r($data, true));
        if($id){
            $employeeCfg_tab->where('id='.$id)->save($data);
        }else{
            $data['cId'] = $cid;
            $id = $employeeCfg_tab->add($data);
        }
        if(is_numeric($id)){
            Output::instance()->resultCode();
            return;
        }
        Output::instance()->resultCode(code_sql_error);
    }
    /**
     * 获取员工信息
     * @param $id /员工id
     */
    public function getEmployeeInfoById($id)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUserModel = M('customer_user');
        Session::switchCustomer($cid);
        $result = $customerUserModel->where('id='.$id)->find();
        if (!$result) {
            Output::instance()->object([
                'code'=>1,
                'msg'=>'数据读写错误'
            ]);
            return;
        }
        Output::instance()->object([
            'code'=>0,
            'results'=>$result
        ]);
    }




    /**
     * 员工二级标签列表
     */
    public function customerTagList($keyword = '', $start = 0, $limit = 100)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagModel = M('customer_tag');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $where['groups.cid'] = array('eq', $cid);
        $where['tag.deleted'] = array('eq', 0);
        empty($keyword) ? '' : $where['tag.tagName'] = array('like','%'.$keyword.'%');
        $arr = $customerTagModel->alias('tag')->where($where)->join("wx_customer_tag_group as groups On tag.groupId=groups.id")->limit($start,$limit)->order('tag.createTime desc')->field('tag.*,groups.groupName')->select();
        $count = $customerTagModel->alias('tag')->where($where)->join("wx_customer_tag_group as groups On tag.groupId=groups.id")->count();

        /**4.返回数据*/
        if (!empty($arr)) {
            $Out = [
                'code' => 0,
                'msg' => '获取分组标签列表成功',
                'data' => $arr,
                'count' => $count,
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '获取分组标签列表失败',
                'data' => [],
                'count' => 0,
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 员工二级分类删除
     * @param $id 员工id
     */
    public function customerTagDelete($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.实例化数据库表*/
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $miContentTagModel = M('customer_tag');
        Session::switchCustomer($cid);

        /**3.删除标签*/
        $result = $miContentTagModel->where("id=$id")->setField('deleted', 1);
        $name = $miContentTagModel->where("id=$id")->getField('tagName');

        /**4.判断是否删除成功*/
        if ($result) {
            R('Log/add',array('employeeLabel', '', '员工标签', op_delete, $miContentTagModel->getLastSql(), '删除员工标签：' . $name));
            Output::instance()->resultCode(code_success);
        } else {
            Output::instance()->resultCode(code_sql_error);
        }
    }

    /**
     * 员工二级分类修改/添加
     * @param $id       /员工id
     * @param $tagName  /员工二级分类名称
     * @param $description /描述
     * @param $number /编号
     * @param $picUrl /封面
     * @param $title /标题
     * @param $groupId /对应一级分类id
     */
    public function customerTagAdd($id = '', $tagName, $description = '', $number = '', $picUrl = '', $title = '', $groupId = '')
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagModel = M('customer_tag');
        $customerTagGroupModel = M('customer_tag_group');
        Session::switchCustomer($cid);

        /**4.不存在则添加*/
        $data['tagName'] = $tagName;
        $data['description'] = $description;
        $data['number'] = $number;
        $data['picUrl'] = $picUrl;
        $data['title'] = $title;
        if(!$groupId){
            $groupId=$customerTagGroupModel->where("groupName='默认' and cId=$cid")->field("id")->find();
            $groupId= $groupId['id'];
        }
        if(!$groupId){
            $data['groupName']='默认';
            $data['deleted']=0;
            $data['cid']=$cid;
            $data['createTime']=date("Y-m-d H:i:s");
            $groupId = $customerTagGroupModel->add($data);
        }
        $data['groupId'] = $groupId;
        $data['cid'] = $cid;

        $data['updateTime'] = date('Y-m-d H:i:s');
        if ($id) {
            $result = $customerTagModel->where(['id' => $id])->save($data);
        } else {
            $data['deleted'] = 0;
            $data['createTime'] = date('Y-m-d H:i:s');
            $result = $customerTagModel->add($data);
        }


        /**5.判断是否添加成功*/
        if (is_numeric($result)) {
            if (!$id) {
                R('Log/add', array('employeeLabel', '', '员工标签', op_add, $customerTagModel->getLastSql(), '添加员工标签' . $tagName));
            } else {
                R('Log/add', array('employeeLabel', '', '员工标签', op_update, $customerTagModel->getLastSql(), '修改员工标签' . $tagName));
            }
            $Out = [
                'code' => 0,
                'msg' => '保存成功',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        } else {
            $Out = [
                'code' => 1,
                'msg' => '保存失败',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        }


    }

    /**
     * 员工二级标签详情
     * @param $id      标签id
     */
    public function customerTagDetail($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        /**2.实例化数据库表*/
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerTagModel = M('customer_tag');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $tagInfo = $customerTagModel->alias('Tag')->where(['Tag.id' => $id])->join("wx_customer_tag_group as groups On Tag.groupId=groups.id")->field('Tag.*,groups.groupName')->find();
        /**4.返回标签信息返回*/
        $Out = [
            'code' => 1,
            'msg' => '获取标签信息',
            'data' => $tagInfo,
        ];
        Output::instance()->object($Out);
    }


    /**
     * 员工一二级标签列表
     */
    public function getCustomerTag()
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagGroupModel = M('customer_tag_group');
        $customerTagModel = M('customer_tag');
        Session::switchCustomer($cid);

        /**3.查询数据*/
        $where['cid'] = array('eq', $cid);
        $where['deleted'] = array('eq', 0);
        $arr = $customerTagGroupModel->where($where)->select();
        foreach ($arr as $k => $v) {
            $tag = $customerTagModel->where(['groupId' => $v['id']])->select();
            $arr[$k]['tag'] = $tag;
        }

        /**4.返回数据*/
        if (!empty($arr)) {
            $Out = [
                'code' => 0,
                'msg' => '获取分组标签成功',
                'data' => $arr,
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '获取分组标签失败',
                'data' => [],
            ];
            Output::instance()->object($Out);
        }

    }

    /**
     * 员工一级分类添加
     * @param $groupName     /一级分类名称
     */
    public function customerTagGroupAdd($id = '', $groupName)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagGroupInfoModel = M('customer_tag_group');
        Session::switchCustomer($cid);

        /**4.不存在则添加*/
        $data['groupName'] = $groupName;
        $data['updateTime'] = date('Y-m-d H:i:s');
        if ($id) {
            $result = $customerTagGroupInfoModel->where(['id' => $id])->save($data);
        } else {
            $data['cid'] = $cid;
            $data['deleted'] = 0;
            $data['createTime'] = date('Y-m-d H:i:s');
            $result = $customerTagGroupInfoModel->add($data);
        }
        $sql = $customerTagGroupInfoModel->getLastSql();


        /**5.判断是否添加成功*/
        if (is_numeric($result)) {
            if (!$id) {
                R('Log/add',array('employeeLabel', '', '员工标签', op_add, $sql, '添加员工标签分组：' . $groupName));
            } else {
                R('Log/add',array('employeeLabel', '', '员工标签', op_update, $sql, '更新员工标签分组：' . $groupName));
            }
            $Out = [
                'code' => 0,
                'msg' => '添加成功',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        } else {
            $Out = [
                'code' => 1,
                'msg' => '添加失败',
                'data' => []
            ];
            Output::instance()->object($Out);
            return;
        }


    }

    /**
     * 员工一级分类删除
     * @param $groupId     分组Id
     */
    public function customerGroupDelete($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagGroupInfoModel = M('customer_tag_group');
        Session::switchCustomer($cid);

        /**3.删除*/
        $where['id'] = array('eq', $id);
        $where['cid'] = array('eq', $cid);
        $result = $customerTagGroupInfoModel->where($where)->setField('deleted', 1);
        $sql = $customerTagGroupInfoModel->getLastSql();
        $groupName = $customerTagGroupInfoModel->where($where)->getField('groupName');

//        $formTagModel->where(['groupId' => $groupId])->setField('deleted', 1);

        /**4.判是否删除成功断*/
        if (is_numeric($result)) {
            R('Log/add',array('employeeLabel', '', '员工标签', op_delete, $sql, '删除员工标签分组' . $groupName));
            $Out = [
                'code' => 0,
                'msg' => '删除成功',
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 0,
                'msg' => '删除失败',
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 获取员工一级分类详情
     * @param $id 表单一级分类id
     */
    public function customerGroupDetail($id)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagGroupInfoModel = M('customer_tag_group');
        Session::switchCustomer($cid);

        /**3.查询数据 */
        $where['id'] = array('eq', $id);
        $arr = $customerTagGroupInfoModel->where($where)->find();

        /**4.返回数据*/
        if (!empty($arr)) {
            $Out = [
                'code' => 0,
                'msg' => '获取分组标签成功',
                'data' => $arr,
            ];
            Output::instance()->object($Out);
        } else {
            $Out = [
                'code' => 1,
                'msg' => '获取分组标签失败',
                'data' => [],
            ];
            Output::instance()->object($Out);
        }
    }

    /**
     * 员工分组列表
     * @param $start 分页开始条数
     * @param $limit 分页每页条数
     */
    public function customerGroupList($keyword = '', $start = 0, $limit = 10)
    {
        /**1.判断用户是否登录*/
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /**2.实例化数据库表*/
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $customerTagGroupInfoModel = M('customer_tag_group');
        Session::switchCustomer($cid);

        /**3.删除*/
        $where['cid'] = array('eq', $cid);
        $where['deleted'] = array('eq', 0);
        empty($keyword) ? '' : $where['groupName'] = array("like","%".trim($keyword)."%");
        $GroupInfo = $customerTagGroupInfoModel->where($where)->limit($start,$limit)->order('createTime desc')->select();
        $count = $customerTagGroupInfoModel->where($where)->count();

        /**4.返回*/
        $Out = [
            'code' => 0,
            'msg' => '获取标签分组标签成功',
            'data' => $GroupInfo,
            'count' => $count,
        ];
        Output::instance()->object($Out);

    }

	/**
	 *初始化角色
	 * cid cid
	 */
	public function customerInitialRole($cid){
		$this->vendorRole($cid);
		$this->businessRole($cid);
		$this->operationCenterAdminRole($cid);
		$this->marketCenterAdminRole($cid);
		$this->clientCenterAdminRole($cid);
		$this->contentCenterAdminRole($cid);
		$this->orderInfoAdminRole($cid);
		$this->newSettlementAdminRole($cid);
	}

	/**
	 * 初始化商家渠道商角色及对应权限
	 * $v cid
	 */
	public function vendorRole($v){
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'vendor', '商家', '1', '1', '')";
		$vendorId = M()->execute($sql);
		$vendorId = M()->getLastInsID();
		log::write('vendor-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '262', $vendorId),($v, '263', $vendorId),($v, '264', $vendorId),($v, '265', $vendorId),($v, '266', $vendorId),
($v, '146', $vendorId),($v, '136', $vendorId),($v, '138', $vendorId);";
		M()->query($sql1);
		log::write('vendor-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化系统管理员角色及对应权限
	 * $v cid
	 */
	public function businessRole($v){
		/*---系统管理员----*/
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'business', '系统管理员', '0', '1', '')";
		$businessId = M()->execute($sql);
		$businessId = M()->getLastInsID();
		log::write('business-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '246', $businessId),($v, '139', $businessId),($v, '225', $businessId),($v, '130', $businessId),($v, '146', $businessId),
($v, '138', $businessId),($v, '125', $businessId),($v, '233', $businessId),($v, '250', $businessId),($v, '255', $businessId),
($v, '256', $businessId),($v, '276', $businessId),($v, '251', $businessId),($v, '239', $businessId),($v, '240', $businessId),
($v, '245', $businessId),($v, '247', $businessId),($v, '123', $businessId),($v, '237', $businessId),($v, '257', $businessId),
($v, '262', $businessId),($v, '263', $businessId),($v, '264', $businessId),($v, '265', $businessId),($v, '266', $businessId),
($v, '267', $businessId),($v, '268', $businessId),($v, '269', $businessId),($v, '234', $businessId),($v, '136', $businessId);";
		M()->query($sql1);
		log::write('business-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化运营中心管理员角色及对应权限
	 * $v cid
	 */
	public function operationCenterAdminRole($v){
		/*---运营管理员----*/
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'operationCenterAdmin', '运营中心管理员', '1', '0', '')";
		$operationCenterAdminId = M()->execute($sql);
		$operationCenterAdminId = M()->getLastInsID();
		log::write('operationCenterAdmin-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '262', $operationCenterAdminId),($v, '263', $operationCenterAdminId),($v, '267', $operationCenterAdminId),($v, '268', $operationCenterAdminId),($v, '269', $operationCenterAdminId),
($v, '234', $operationCenterAdminId),($v, '257', $operationCenterAdminId),($v, '246', $operationCenterAdminId),($v, '146', $operationCenterAdminId),($v, '136', $operationCenterAdminId),
($v, '138', $operationCenterAdminId);";
		M()->query($sql1);
		log::write('operationCenterAdmin-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化营销中心管理员角色及对应权限
	 * $v cid
	 */
	public function marketCenterAdminRole($v){
		/*---营销管理员----*/
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'marketCenterAdmin', '营销中心管理员', '1', '0', '')";
		$marketCenterAdminnId = M()->execute($sql);
		$marketCenterAdminnId = M()->getLastInsID();
		log::write('marketCenterAdmin-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '125', $marketCenterAdminnId),($v, '233', $marketCenterAdminnId),($v, '250', $marketCenterAdminnId),($v, '255', $marketCenterAdminnId),($v, '146', $marketCenterAdminnId),
($v, '136', $marketCenterAdminnId),($v, '138', $marketCenterAdminnId);";
		M()->query($sql1);
		log::write('marketCenterAdmin-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化客户中心管理员角色及对应权限
	 * $v cid
	 */
	public function clientCenterAdminRole($v){
		/*---客户中心管理员----*/
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'clientCenterAdmin', '客户中心管理员', '1', '0', '')";
		$clientCenterAdminId = M()->execute($sql);
		$clientCenterAdminId = M()->getLastInsID();
		log::write('clientCenterAdmin-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '256', $clientCenterAdminId),($v, '276', $clientCenterAdminId),($v, '251', $clientCenterAdminId),($v, '146', $clientCenterAdminId),($v, '136', $clientCenterAdminId),
($v, '138', $clientCenterAdminId);";
		M()->query($sql1);
		log::write('clientCenterAdmin-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化内容中心管理员及对应权限
	 * $v cid
	 */
	public function contentCenterAdminRole($v){
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'contentCenterAdmin', '内容中心管理员', '1', '0', '')";
		$contentCenterAdminId = M()->execute($sql);
		$contentCenterAdminId = M()->getLastInsID();
		log::write('contentCenter-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '239', $contentCenterAdminId),($v, '240', $contentCenterAdminId),($v, '245', $contentCenterAdminId),($v, '247', $contentCenterAdminId),($v, '146', $contentCenterAdminId),
($v, '136', $contentCenterAdminId),($v, '138', $contentCenterAdminId);";
		M()->query($sql1);
		log::write('contentCenter-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化订单中心管理员角色及对应权限
	 * $v cid
	 */
	public function orderInfoAdminRole($v){
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'orderInfoAdmin', '订单中心管理员', '1', '0', '')";
		$orderInfoAdminId = M()->execute($sql);
		$orderInfoAdminId = M()->getLastInsID();
		log::write('orderInfoAdmin-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '237', $orderInfoAdminId),($v, '146', $orderInfoAdminId),($v, '136', $orderInfoAdminId),($v, '138', $orderInfoAdminId);";
		M()->query($sql1);
		log::write('orderInfoAdmin-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 初始化结算中心管理员角色及对应权限
	 * $v cid
	 */
	public function newSettlementAdminRole($v){
		/*---结算中心管理员----*/
		$sql = "INSERT INTO `wx_role`(cid,englishRole,chineseRole,manual,isSys,auage) VALUES
                    ($v, 'newSettlementAdmin', '结算中心管理员', '1', '0', '')";
		$newSettlementAdminId = M()->execute($sql);
		$newSettlementAdminId = M()->getLastInsID();
		log::write('newSettlementAdmin-'.$v.'-'.M()->getLastSql());
		$sql1 = "INSERT INTO `wx_role_module_group`(cid,groupId,agent) VALUES
($v, '259', $newSettlementAdminId),($v, '260', $newSettlementAdminId),($v, '146', $newSettlementAdminId),($v, '136', $newSettlementAdminId),($v, '138', $newSettlementAdminId);";
		M()->query($sql1);
		log::write('newSettlementAdmin-role'.$v.'-'.M()->getLastSql());
	}

	/**
	 * 系统管理角色关联客户
	 * $v cid
	 */
	public function customerBusinessRole($cid,$id){
		$roleModel = D('role');
		$cuRoleModel = D('customer_user_role');
		$roleId = $roleModel->where(['cid' => $cid, 'englishRole' => 'business'])->getField('id');
		if($roleId){
			$data['cid'] = $cid;
			$data['userId'] = $id;
			$data['roleId'] = $roleId;
			$cuRoleModel->add($data);
		}

	}
}


